﻿
//=======================================================================================
//作者：         于俊杰
//
//创建时间：     2008-11-24
//最后修改时间： 2009-10-09 
//
//说明：         New GUI frame beta 1.00
//
//版本：         beta 1.20091009.2210
//
//=======================================================================================
//                               Copyright (c) 2009 XM3
//=======================================================================================


//=======================================================================================
//类名 ： Sail
//说明 ： 扩展 String、Array
//创建 ： 2009-10-09 22:10:00 
//变更 ： 
//
//=======================================================================================

Sail = {};

Sail.apply = function(o, c, defaults){
    if(defaults){
        Sail.apply(o, defaults);
    }
    if(o && c && typeof c == 'object'){
        for(var p in c){
            o[p] = c[p];
        }
    }
    return o;
};

Sail.applyExFunc = function(o, c, defaults){
    if(defaults){
        Sail.apply(o, defaults);
    }
    
    if(o && c && typeof c == 'object'){
        for(var p in c){
            if(typeof c[p] !=='function')
                o[p] = c[p];
        }
    }
    return o;
};    

Sail.apply2 = function(o, c, defaults){
    if(defaults){
        Sail.apply(o, defaults);
    }
    if(o && c && typeof c == 'object'){
        for(var p in c){
            if(typeof c[p]=='object' && !(c[p] instanceof Array)){
                if(o[p]==undefined) o[p]={};
                if(o[p] instanceof Array){
                    o[p] = c[p];
                }else{
                    Sail.apply2(o[p] , c[p]);
                }
            }
            else
                o[p] = c[p];
        }
    }
    return o;
};

Sail.applyAbsolute = Sail.apply2;

(function(){
    Sail.apply(Sail, {

        namespace : function() {
            var a=arguments, o=null, i, j, d, rt;
            for (i=0; i<a.length; ++i) {
                d=a[i].split(".");
                rt = d[0];
                eval('if (typeof ' + rt + ' == "undefined"){' + rt + ' = {};} o = ' + rt + ';');
                for (j=1; j<d.length; ++j) {
                    o[d[j]]=o[d[j]] || {};
                    o=o[d[j]];
                }
            }
        },
        

        extend : function(){
            //debugger;
            // inline overrides
            var io = function(o){
                for(var m in o){
                    this[m] = o[m];
                }
            };
            return function(sb, sp, overrides){
                
                if(typeof sp == 'object'){
                    overrides = sp;
                    sp = sb;
                    sb = function(){sp.apply(this, arguments);};
                }
                var F = function(){}, sbp, spp = sp.prototype;
                F.prototype = spp;
                sbp = sb.prototype = new F();
                sbp.constructor=sb;
                sb.superclass=spp;
                if(spp.constructor == Object.prototype.constructor){
                    spp.constructor=sp;
                }
                //alert();
                sb.override = function(o){
                    Sail.override(sb, o);
                };
                sbp.override = io;
                //debugger;
                Sail.override(sb, overrides);
                return sb;
            };
        }(),
        

        override : function(origclass, overrides){
            if(overrides){
                var p = origclass.prototype;
                //debugger;
                for(var method in overrides){

                    //-------------------------------------------------------------------
                    //-------------------------------------------------------------------
                    if(typeof overrides[method]=='object' && !(overrides[method] instanceof Array)){
                        //debugger;
                        if(p[method]==undefined) p[method]={};
                        if(p[method] instanceof Array){
                            
                            p[method] = [].concat(overrides[method]);
                        }else{
                            Sail.apply2(p[method] , overrides[method]);
                        }
                    }
                    else
                        p[method] = overrides[method];
                }
            }
        },

        applyIf : function(o, c){
            if(o && c){
                for(var p in c){
                    if(typeof o[p] == "undefined"){ o[p] = c[p]; }
                }
            }
            return o;
        },
                

        request : function(config){
            Ext.Ajax.request(config);
        },
        postData : function(_url,postData,successFn,errorFn,source){
            if(_url=="") {
                Ext.Msg.alert("信息","没有找到url！");
                return;
            }
            
            Ext.Ajax.request({
                url: _url,method: 'POST',params: postData,
                success: function(action) {
                    var getResponse = eval("("+action.responseText+")"); 
                    var flag = getResponse.dataset.response.success;
                    
                    if(typeof successFn =="function") {
                        successFn.call(this,flag,getResponse,source);
                    }else{
                        Ext.Msg.alert('提示：', '成功！'); return true;
                    }
                },
                failure: function(action) {
                    var _status = action.status; 
    
                    if(typeof errorFn =="function") {
                        errorFn.call(this,false,_status);
                    }else{
                        Ext.Msg.alert('提示：', '提交数据失败！'); return false;
                    }
                }
            });
        },
        
        confirm : function(fn){
            Ext.Msg.confirm("注意", "您确认要“删除”指定的记录吗？", function(yes_or_no) {
                if (yes_or_no != 'yes') return;
                
                fn.apply();
            });
        },
        
        callLater : function(fRef, argu1, argu2){
            return (function() { 
                fRef(argu1, argu2); 
            }); 
        },
        
        showMsg : function(title,msg){
            if(msg==undefined){
                this.showErrorMessage('提示信息',title,'info');
            }else{
                msg = msg+"<br><p style='width:200px;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>";
                Ext.Msg.alert(title,msg);
            }
        },
        showErrorMessage : function(title,message,type){
            var iconType = (type=="warning")?Ext.MessageBox.WARNING:((type=="info")?Ext.MessageBox.INFO:((type=="error")?Ext.MessageBox.ERROR:Ext.MessageBox.QUESTION));
            Ext.MessageBox.show({
                title: title,
                msg: message,
                buttons: Ext.MessageBox.OK,
                icon: iconType
            });
        },
        
        createDiv : function(config){
            var div = document.createElement( "DIV" );    
            Sail.apply(div,config);
                        
            //if(this.hidden) container.style.display = "none";
            
            document.body.insertBefore(div);
            return div;
        },
        addDiv2 : function(fDiv,config){
            var div = document.createElement( "DIV" );    
            Sail.apply(div,config);

            fDiv.appendChild(div);
            //fDiv.insertBefore(div);
            return div;            
        },
        applyStyle : function(div,config){
            Sail.apply(div.style,config);
        },
        setPosition : function(div,_left,_top){
            var config= {left:_left,top:_top};
            Sail.apply(div.style,config);
        },
        isObjArray : function(a){
            if(a instanceof Array){ 
                if(a.length>0){
                    if((typeof a[0] == 'object') && (!(a[0] instanceof Array))){
                        return true;
                    }else{
                        return false;
                    }
                }else{
                    return false;
                }
            }else{
                return false;
            }           
        },
        copyObjArray : function(a){
            var ra = new Array();
            for(var i=0;i<a.length;i++){
                var o = {};
                Sail.apply(o,a[i]);
                ra.push(o);
            }
            return ra;
        },
        copyObjArray2 : function(a){
            var ra = new Array();
            for(var i=0;i<a.length;i++){
                var o = {};
                //-----------------------------------------------
                //对象的深层次copy啊，，，日，，
                //暂时先这么着，，，
                //2009-04-09 22:46
                //-----------------------------------------------
                o.items = Sail.copyObjArray(a[i].items);
                //Sail.apply(o,a[i]);
                ra.push(o);
            }
            return ra;
        },
        copyObjArray3 : function(a){
            var ra = new Array();
            
            for(var i=0;i<a.length;i++){
                var ta = new Array();
                for(var j=0;j<a[i].length;j++){
                    if(typeof a[i][j] =='object'){
                        var o = {};
                        Sail.apply(o,a[i][j]);
                        ta.push(o);
                    }else{
                        ta.push(a[i][j]);
                    }
                }
                ra.push(ta);
            }
            return ra;
        },
        
        
        getValueFormObjArray : function(oa,field){
            var ra = [];
            for(var i=0;i<oa.length;i++){
                ra.push(oa[i][field]||"");
            }
            return ra;
        },


        getSubObj:function(fo,subs){
            try{
                if(typeof subs == "string"){
                    subs = subs.split(".");
                }
                
                if(subs.length==1) return fo[subs[0]];
    
                var pp = (subs[0].indexOf("[")==-1)?"":subs[0].split("[")[1].replace("]","");
                fo = (subs[0].indexOf("[")==-1)?fo[subs[0]]:fo[subs[0].split("[")[0]][pp];
    
                //fo = fo[subs[0]];
                subs.splice(0,1);
                return Sail.getSubObj(fo,subs);
            }catch(e){
                //alert("没有找到指定的子对象。");
                return null;
            }
        },
        
        open:function(_url,_mode,_data,w,h){
            var sendData = {
                mode : _mode,
                data : _data
            };
            var chrValue=window.showModalDialog(_url,sendData,'dialogWidth:'+w+'px;dialogHeight:'+h+'px;center:1;scroll:1;help:0;status:0');
    
            return chrValue;
        },
        
        findValue : function(oa,fieldName,fieldValue,resultField){
            for(var i=0;i<oa.length;i++){
                if(oa[i][fieldName]==fieldValue){
                    return oa[i][resultField]||"";
                }
            }
            return "";
        },


        getLabelWidth : function(label,cls){
            var td;
            if(document.getElementById('sail.getLabelWidth')==undefined){
                td = document.createElement("font");
                td.id='sail.getLabelWidth';
                td.innerText = label;
                td.style.font=(cls==undefined)?'normal 12px verdana':cls;
                //td.style.border='1px #ff0000 solid';
                document.body.insertBefore(td);
            }else {
                td = document.getElementById('sail.getLabelWidth');
                td.style.display='';
                td.innerText = label;
                td.style.font=(cls==undefined)?'normal 12px verdana':cls;
            }
                
            var width = td.offsetWidth;
            td.style.display='none';
            
            return width;
        },
        
        getLabelHeight : function(label,width,cls){
            return;
            var td;
            if(document.getElementById('sail.getLabelHeight')==undefined){
                td = document.createElement("font");
                td.id='sail.getLabelWidth';
                td.innerText = label;
                td.style.font=(cls==undefined)?'normal 12px verdana':cls;
                //td.style.border='1px #ff0000 solid';
                document.body.insertBefore(td);
            }else {
                td = document.getElementById('sail.getLabelHeight');
                td.style.display='';
                td.innerText = label;
                td.style.font=(cls==undefined)?'normal 12px verdana':cls;
            }
                
            var width = td.offsetWidth;
            td.style.display='none';
            
            return width;
        },


        testRegex : /^\d{2}-\d{5}/,
            
        isTime : function(t){
            var re = /^(([0-1]?\d)|([2][0-3]))?\:?([0-5]?\d)?\:?([0-5]?\d)?$/g;
            return re.test(t);
        },
        get: function(_objid) {
            return document.getElementById(_objid);
        },

        getHrefSearch : function(){
            var _search = document.location.search;
            if(_search == undefined||_search=="") return {};
            //debugger;
            var info = _search.substr(1);            
            var a = info.split("&");
            var ro = {data:{}};
            for(var i=0;i<a.length;i++){
                var v = a[i].split('=');
                ro["data"][v[0]]=v[1];
            }
            return ro;
        },
        
        formatNumber2 : function(value){
            return Math.round(value*100)/100;
        },

        formatNum : function(v,decimalPrecision){
            var value = parseFloat(v);
            if(isNaN(value)) return null;
            
            if(decimalPrecision==undefined)
                return Math.round(value*100)/100;
            else{
                if(decimalPrecision==0){
                    return Math.round(value);
                }else{
                    var tmp = Math.pow(10,decimalPrecision);
                    return Math.round(value*tmp)/tmp;
                }
            }
        },
        
        formatWZ : function(value){
            return ""+value+"万支";
        },
        
        formatPercent : function(value){
            //return Math.round(value*10000)/100+"%";
        	return value+"%";
        },
        formatPercent2 : function(value){
        	return Math.round(value*10000)/100+"%";
        },
        
        formatDate : function(v){
          if (v == undefined) v = "";
          if(v.indexOf('-')==-1)
            return v.substr(0,4)+"-"+v.substr(4,2)+"-"+v.substr(6,2);
          else
            return v;
        },
        
        toDate : function(v){
            var flag = (v.indexOf('-')==-1)?true:false;
            var year = v.substr(0,4);
            var month = (flag)?v.substr(4,2):v.substr(5,2);
            var day = (flag)?v.substr(6,2):v.substr(8,2);
            month = parseInt(month)-1;
            return new Date(year,month,day);
        },
        toTime : function(value){
            if(value=="") return "";
            
            if(value.length>6 && value.indexOf(":")==-1)
                value = value.left(6);
    
            if(value.indexOf(":")==-1&&value.length==6){
                if(!Sail.isTime(value)) return "";
                var vs =""+value;
                return vs.substr(0,2)+":"+vs.substr(2,2)+":"+vs.substr(4,2);
            }
            
            
            var vs = value.split(":");
            if(vs.length==1){
                var vback = value;
                vs = [];
    
                var h = parseInt(vback.left(2),10)||0;
                vs.push((h>23)?vback.left(1):""+h);
                vback = ((h>23)?vback.right(vback.length-1):vback.right(vback.length-2))
                
                var h = parseInt(vback.left(2),10)||0;
                vs.push((h>59)?vback.left(1):""+h);
                vback = ((h>59)?vback.right(vback.length-1):vback.right(vback.length-2))
                
                vs.push((parseInt(vback,10)>59)?"0":vback);
            }
            
            for(var i=0;i<vs.length;i++){
                vs[i]=(vs[i]=="")?"00":vs[i];
                
                if(vs[i].length==1 && parseInt(vs[i],10)<10&&parseInt(vs[i],10)!=0){
                    vs[i]="0"+vs[i];
                }
                if(vs[i]=="0") vs[i]="00";
            }
            return vs.join(":");
        },
        
        num2String : function(num,format){
            var str = ""+num;
            var formatLen = format.length;
            
            if(str.length<formatLen){
                var len = formatLen-str.length;
                for(var i=0;i<len;i++)
                    str="0"+str;
            }
            
            return str;
        },
        
        getYear:function(){
            var dt = new Date();
            var y = dt.getYear();
            return y;
            
            //var m = dt.getMonth()+1;      //原烟业务年度才需要此判断
            //return (m<7)?y-1:y;
        },
        getMonth : function(){
            var dt = new Date();
            return dt.format('n');
        },
        getDay : function(){
            var dt = new Date();
            return dt.format('Ymd');
        },
        
        getDateListBetween : function(begin,end){
        },
        
        showtree : function(config){
                    var pathname=location.pathname;
                    var ctx="";
                    if (pathname.substr(0,1)=="/"){
                      ctx=location.pathname.split("/")[1];
                    }else{
                      ctx=location.pathname.split("/")[0];
                    }
            var windowPath = "/"+ctx+"/business/public/commonTree.html";       //公用页面路径
            
            config.mode = "select";          //2009-08-07 add by yujunjie for spsc
            return window.showModalDialog(windowPath,config,'dialogWidth:'+config.width+'px;dialogHeight:'+config.height+'px;center:1;scroll:1;help:0;status:0');
        },
        
        getX: function(o) {
            var l=o.offsetLeft;
            while(o=o.offsetParent){
                l+=o.offsetLeft;
            }
            return l;
        },
        
        getY: function(o) {
            var t=o.offsetTop;
            while(o=o.offsetParent){
                t+=o.offsetTop;
            }
            return t;
        },
        
        exportExcel : function(outPutData,fileName){     
            
            var createFlag="";
            
            if(typeof(EXPORT_OBJECT09)!="object"){     
                document.body.insertAdjacentHTML("afterBegin","<OBJECT id=EXPORT_OBJECT09 style='display:none' classid=clsid:0002E510-0000-0000-C000-000000000046 ></Object>");     
            }     
        
            if(typeof(EXPORT_OBJECT10)!="object"){     
                document.body.insertAdjacentHTML("afterBegin","<OBJECT id=EXPORT_OBJECT10 style='display:none' classid=clsid:0002E551-0000-0000-C000-000000000046 ></Object>");     
            }     
        
            if(typeof(EXPORT_OBJECT11)!="object"){     
                document.body.insertAdjacentHTML("afterBegin","<OBJECT id=EXPORT_OBJECT11 style='display:none' classid=clsid:0002E559-0000-0000-C000-000000000046 ></Object>");     
            }     

            with(EXPORT_OBJECT11){     
                DataType  = "HTMLData";     
                HTMLData  = outPutData;    
                try{     
                    Export(fileName,0,2);     
                    return;   
                }     
                catch (e){
                    createFlag="false";     
                }     
            }     

            with(EXPORT_OBJECT10){     
                DataType  = "HTMLData";     
                HTMLData  = outPutData;     
                try{     
                    Export(fileName,0);     
                    return;   
                }     
                catch (e){
                    createFlag="false";     
                }     
            }     
                      
            if(createFlag=="false"){
                with(EXPORT_OBJECT09)
                {     
                    DataType  = "HTMLData";     
                    HTMLData  = outPutData;     
                    try{     
                        ActiveSheet.Export(fileName,0);     
                        alert('导出EXCEL文档完毕');  
                        return;   
                    }     
                    catch (e){     
                        alert('导出Excel表失败，请确定已安装Excel2000(或更高版本),并且没打开同名xls文件');     
                    } 
                }
            }    
        },
        
        exportExcel_11 : function(dataObj,fileName){
            if(typeof(EXPORT_OBJECT11)!="object"){     
                document.body.insertAdjacentHTML("afterBegin","<OBJECT id=EXPORT_OBJECT11 style='display:none' classid=clsid:0002E559-0000-0000-C000-000000000046 ></Object>");     
            }     
            
            var xlsheet = EXPORT_OBJECT11.Worksheets(1);
            
            //debugger;
            xlsheet.Rows(1).HorizontalAlignment =EXPORT_OBJECT11.Constants.xlHAlignCenter;
            
            //xlsheet.Cells(1,1).Interior.ColorIndex = 4;
            xlsheet.Cells(1,1).Borders.LineStyle = 1;
            xlsheet.Cells(1,1).Value = "testa";
            xlsheet.Cells(1,1).Font.Color = 'red';
            xlsheet.Cells(1,1).Font.Bold = true;
            //xlsheet.Cells(1,1).width = 200;
            
            
            xlsheet.Rows(2).HorizontalAlignment =1;
            xlsheet.Cells(2,2).Interior.Color = "#ff0000";
            xlsheet.Cells(2,2).Borders.LineStyle = 1;
            xlsheet.Cells(2,2).Value = "testbbbb";
            
            
            EXPORT_OBJECT11.Export(fileName,0,2);  
            return;            
        }
        
    });

})();






//=======================================================================================
//类名 ： Sail.DIV
//说明 ： 扩展 String、Array
//创建 ： 2009-10-09 22:10:00 
//变更 ： 
//
//=======================================================================================

Sail.DIV    = function(config){
    this.el = null;
    this.defaultWidth  = 100;
    this.defaultHeight = 20;

    //this.border   = "0px #ff0000 solid";
    this.position = "absolute";
    
    //-----------------------------------------------------------------------------------
    Sail.apply(this, config);
    this.create();    
};
Sail.DIV.prototype = {
    
    //===================================================================================
    //方法 ： create
    //参数 ： 
    //返回 :  
    //说明 ： 创建
    //===================================================================================
    create   : function(config){
        Sail.apply(this,config);

        this.left  = (this.left  ==undefined)?0:this.left;
        this.top   = (this.top   ==undefined)?0:this.top;
        //this.width = (this.width ==undefined)?this.defaultWidth:this.width;
        //this.height= (this.height==undefined)?this.defaultHeight:this.height;
        this.zIndex= (this.zIndex==undefined)?10:this.zIndex;
    
        //-------------------------------------------------------------------------------
        //创建
        //-------------------------------------------------------------------------------
        this.el  = document.createElement( "DIV" );    
        //if(config!=undefined && config.className!=undefined)      //???无效！！！！
        //    this.el.className=config.className;
        //this.el.className = 'test_yjj';

        var _style  = {            
            left    : this.left,
            top     : this.top,
            zIndex  : this.zIndex,
            position: this.position
            //border  : this.border
        };

        if(this.style!=undefined)   Sail.apply(_style,this.style);
        if(this.border!=undefined)  _style.border= this.border;
        if(this.width!=undefined)   _style.width = this.width;
        if(this.height!=undefined)  _style.height= this.height;
        Sail.apply(this.el.style,_style);

        
        this.el.id = "["+this.el.uniqueID+"]";
        this.id = this.el.id;
        
        if(this.parent.el!=undefined)
            this.parent.el.appendChild(this.el);
        else
            this.parent.appendChild(this.el);
        
        return this;
    },
    
    clone : function(){
        return this.el.cloneNode(false);
    },
    
    applyStyle : function(style){
        Sail.applyStyle(this.el,style);
    },
    addClass : function(className){
        if(className && !this.hasClass(className)){
            this.el.className = this.el.className + " " + className;
        }
    },
    removeClass : function(className){    
        if(!className || !this.el.className){
            return this;
        }
        if(this.hasClass(className)){
            var re = this.classReCache[className];
            if (!re) {
               re = new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)', "g");
               this.classReCache[className] = re;
            }
            this.el.className =
                this.el.className.replace(re, " ");
        }
    },
    classReCache: {},    
    
    hasClass : function(className){
        return className && (' '+this.el.className+' ').indexOf(' '+className+' ') != -1;
    },
    //===================================================================================
    //方法 ： some functions for get...
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getEl    : function(){ return this.el;  },
    getID    : function(){ return this.id;  },
    getParent: function(){ return this.parent; },
    
    getLeft  : function(){ return this.el.style.left; },
    getTop   : function(){ return this.el.style.top;  },
    getWidth : function(){ return this.el.style.width;},
    getHeight: function(){ return this.el.style.height;}, 
    getOffset: function(){ return {width:this.el.offsetWidth,height:this.el.offsetHeight}; },
    getScroll: function(){ return {width:this.el.scrollWidth,height:this.el.scrollHeight}; },
    
    setLeft  : function(left)  { this.el.style.left  = left; },
    setTop   : function(top)   { this.el.style.top   = top;  },
    setWidth : function(width) { this.el.style.width = width; },
    setHeight: function(height){ this.el.style.height= height; },
    setZIndex: function(zIndex){ this.el.style.zIndex= zIndex; },
    setHTML  : function(html)  { this.el.innerHTML = html; },
    setText  : function(text)  { this.el.innerText = text; },
    
    scroll2  : function(position,step,mode){
        if(position=="h"){ 
            var old = this.el.scrollLeft;
            this.el.scrollLeft = (mode==='increase')?old+step:step;
        }
        else this.el.scrollTop = step;
    },
    setSize  : function(width,height){
        this.setWidth(width);
        this.setHeight(height);
    },
    
    move2: function(left,top){
        this.setLeft(left);
        this.setTop(top);
    },
    
    hide : function() { this.el.style.display = "none"; },
    show : function() { this.el.style.display = ""; }
};




//=======================================================================================
//类名 ： 
//说明 ： 扩展 String、Array
//创建 ： 2009-10-09 22:10:00 
//变更 ： 
//
//=======================================================================================
String.prototype.trim = function(){
    var re = /^\s+|\s+$/g;
    return function(){ return this.replace(re, ""); };
}();

String.prototype.left = function(total_chars){
    return this.substring(0, total_chars);
};

String.prototype.right = function(total_chars){
    return this.substring(this.length-total_chars, this.length);
};

String.prototype.replaceAll = function(find_string, replace_string){
    var temp_string = this;
    var left_string;
    var right_string;
    var start_location;

    var replace_location = temp_string.indexOf(find_string);
    while (replace_location != -1) {
        left_string = temp_string.left(replace_location);
        right_string = temp_string.substring(replace_location + find_string.length);
        temp_string = left_string + replace_string + right_string;
        start_location = replace_location + replace_string.length;
        replace_location = temp_string.indexOf(find_string, start_location);
    }
    return temp_string;
};

String.prototype.toggle = function(value, other){
    return this == value ? other : value;
}

Sail.applyIf(String, {


    escape : function(string) {
        return string.replace(/('|\\)/g, "\\$1");
    },


    leftPad : function (val, size, ch) {
        var result = new String(val);
        if(ch === null || ch === undefined || ch === '') {
            ch = " ";
        }
        while (result.length < size) {
            result = ch + result;
        }
        return result;
    },


    format : function(format){
        var args = Array.prototype.slice.call(arguments, 1);
        return format.replace(/\{(\d+)\}/g, function(m, i){
            return args[i];
        });
    }
});


Array.prototype.indexOf = function(o){
   for (var i = 0, len = this.length; i < len; i++){
      if(this[i] == o) return i;
   }
   return -1;
};

Array.prototype.remove = function(o){
   var index = this.indexOf(o);
   if(index != -1){
       this.splice(index, 1);
   }
   return this;
}

Array.prototype.removeAll = function(o){
    var oa = this;
    var ra = [];

    for(var i = 0; i < oa.length; i++ ){ 
        var temp=oa[i]; 
        if(temp!==o){ 
            ra.push(temp); 
        }
    } 
    
    return ra;
};

Array.prototype.have = function(v){
    var splitChar = arguments[1]||",";
    var v = arguments[0];
    var sa = ""+splitChar+this.join(splitChar)+splitChar;
    return (sa.indexOf(""+splitChar+v+splitChar)==-1)?false:true;
};

Array.prototype.map = function(fun){
	var len = this.length;
	if(typeof fun != "function"){
        throw new TypeError();
    }
	var res = new Array(len);
	var thisp = arguments[1];
	for(var i = 0; i < len; i++){
        if(i in this){
            res[i] = fun.call(thisp, this[i], i, this);
        }
    }
    return res;
};

Array.prototype.replace = function(index,newitem){
    if(index==0){
        return (this.length==1)?[newitem]:[].concat([newitem],this.slice(index+1));
    }
    
    var subArray1 = this.slice(0,index);
    var subArray2 = (index==(this.length-1))?[]:this.slice(index+1);
    var newArray = [].concat(subArray1,[newitem],subArray2);
    subArray1 = null;
    subArray2 = null;
    return newArray; 
    
};

Array.prototype.insertItems = function(after,items){
    var len = this.length;
    
    var subArray1 = this.slice(0,after+1);
    var subArray2 = this.slice(after+1);
    var newArray = [].concat(subArray1,items,subArray2);
    subArray1 = null;
    subArray2 = null;
    return newArray; 
};

Array.prototype.repeated = function(){ 
    
    var oa = this; 
    var ya = new Object(); 
    var ra = []; 
    
    for(var i = 0; i < oa.length; i++ ){ 
        var temp=oa[i]; 
        if(ya[temp]){ 
            ra.push(temp); 
        }else{ 
            ya[temp]=temp; 
        } 
    } 
    return ra; 
} 

Array.prototype.distinct = function(){
    var oa = this; 
    var ya = new Object(); 
    var ra = []; 
    
    for(var i = 0; i < oa.length; i++ ){ 
        var temp=oa[i]; 
        if(ya[temp]==undefined){ 
            ra.push(temp); 
        }
        ya[temp]=temp;  
    } 

    return ra;
}

Array.prototype.sum = function(){
    var v = 0;
    for(var i=0,len=this.length;i<len;i++)
        v+=parseFloat(this[i])||0;
    return v;
}

Array.prototype.max = function(){
    return eval("Math.max("+this.join(',')+")");
}

Array.prototype.min = function(){
    return eval("Math.min("+this.join(',')+")");
}

//var _debugger = [];


//=======================================================================================
//类名 ： 
//说明 ： $
//创建 ： 2009-10-09 22:10:00 
//变更 ： 
//
//=======================================================================================
var _BDC = {items:{}};              //business data changed flag ?
var ISR = {items:{}};               //$方法调用的缓存对象
var sys_deferEvents = {};           //tabs动态加载时，缓存的注册事件发起对象

function $2(info){
    var vs = info.split('.');
    var itemName='';
    
    if(vs.length==1 || vs.length==2){
        var _itemName  = (vs.length==1)?vs[0]:vs[1];
        var _frameName = (vs.length==1)?ISR.page.getFrame(0).name:vs[0];
                
        if(ISR["items"][_frameName][_itemName]!=undefined) {
            return ISR["items"][_frameName][_itemName];
        }
        else{
            var frame = ISR.page.getFrame(_frameName);
            var item = frame.getItem(_itemName);
            if(item!=null) {
                ISR["items"][_frameName][_itemName] = item;
                return item;
            }else{
                //debugger;
                return _itemName;
            }
        }
    }else{
        return null;
    }
}

function $(info){
    var vs = info.split('.');
    var itemName='';
    
    if(vs.length==1 || vs.length==2){
        var _itemName  = (vs.length==1)?vs[0]:vs[1];
        var _frameName = (vs.length==1)?ISR.page.getFrame(0).name:vs[0];
                
        if(ISR["items"][_frameName][_itemName]!=undefined) {
            return ISR["items"][_frameName][_itemName];
        }
        else{
            var frame = ISR.page.getFrame(_frameName);
            var item = frame.getItem(_itemName);
            if(item!=null) {
                ISR["items"][_frameName][_itemName] = item;
                return item;
            }else{
                return new Sail.simulantWidget(_itemName);
            }
        }
    }else{
        return null;
    }
}


Sail.simulantWidget = function(wName){
    this.name = wName||"";
    
    this.isSimulant = true;
    //Sail.apply(this,config);
};

Sail.simulantWidget.prototype = {
    getButton : function(btName){
        return {
            itemName : this.name,
            funcName : 'getButton',
            btName   : btName,
            on       : function(ename,fn,scope){
                sys_deferEvents[this.itemName] = {
                    funcName : 'getButton',
                    btName   : this.btName,
                    eName    : ename,
                    handler  : fn,
                    scope    : scope
                };
            }
        }
    },
    
    addButtonHandler : function(btName,fn,scope){
        sys_deferEvents[this.name] = {
            funcName : 'getButton',
            btName   : btName,
            eName    : 'click',
            handler  : fn,
            scope    : scope
        };
    },
    
    addAction : function(actionName,fn,scope){
        sys_deferEvents[this.name] = {
            funcName : 'addAction',
            actionName : actionName,
            eName    : 'addAction',
            handler  : fn,
            scope    : scope
        };
    }
};

if(Ext.onReady){
    Ext.onReady(function(){
        Ext.QuickTips.init();
    });
}﻿//=======================================================================================
//类名 ： 
//说明 ： Ext 扩展
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================


//=======================================================================================
//类名 ： 
//说明 ： Ext 扩展
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================

Ext.data.PagingMemoryProxy = function(data, config) {
	Ext.data.PagingMemoryProxy.superclass.constructor.call(this);
	this.data = data;
	Ext.apply(this, config);
};

Ext.extend(Ext.data.PagingMemoryProxy, Ext.data.MemoryProxy, {
	customFilter: null,
	
	load : function(params, reader, callback, scope, arg) {
		params = params || {};
		var result;
		try {
			result = reader.readRecords(this.data);
		} catch(e) {
			this.fireEvent("loadexception", this, arg, null, e);
			callback.call(scope, null, arg, false);
			return;
		}
		
		if (this.customFilter!=null) {
			result.records = result.records.filter(this.customFilter);
			result.totalRecords = result.records.length;
		} else if (params.filter!==undefined) {
			result.records = result.records.filter(function(el){
			    if (typeof(el)=="object"){
					var att = params.filterCol || 0;
					return String(el.data[att]).match(params.filter)?true:false;
			    } else {
					return String(el).match(params.filter)?true:false;
			    }
			});
			result.totalRecords = result.records.length;
		}
		
		if (params.sort!==undefined) {
		    var dir = String(params.dir).toUpperCase() == "DESC" ? -1 : 1;
        	    var fn = function(r1, r2){
			    return r1==r2 ? 0 : r1<r2 ? -1 : 1;
        	    };
		    var st = reader.recordType.getField(params.sort).sortType;
		    result.records.sort(function(a, b) {
				var v = 0;
				if (typeof(a)=="object"){
				    v = fn(st(a.data[params.sort]), st(b.data[params.sort])) * dir;
				} else {
				    v = fn(a, b) * dir;
				}
				if (v==0) {
				    v = (a.index < b.index ? -1 : 1);
				}
				return v;
		    });
		}

		if (params.start!==undefined && params.limit!==undefined) {
			result.records = result.records.slice(params.start, params.start+params.limit);
		}
		
		callback.call(scope, result, arg, true);
	}
});



//--------------------------------------------------------------------------------
//JSON 
//--------------------------------------------------------------------------------
if (!Object.prototype.toJSONString) {
    Array.prototype.toJSONString = function (w) {
        var a = [],i,l = this.length,v;

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'object':
                if (v && typeof v.toJSONString === 'function') {
                    a.push(v.toJSONString(w));
                } else {
                    a.push('null');
                }
                break;
            case 'string':
            case 'number':
            case 'boolean':
                a.push(v.toJSONString());
                break;
            default:
                a.push('null');
            }
        }
        return '[' + a.join(',') + ']';
    };

    Boolean.prototype.toJSONString = function () {
        return String(this);
    };

    Date.prototype.toJSONString = function () {
        function f(n) {
            return n < 10 ? '0' + n : n;
        }
        return '"' + this.getUTCFullYear()   + '-' +
                   f(this.getUTCMonth() + 1) + '-' +
                   f(this.getUTCDate())      + 'T' +
                   f(this.getUTCHours())     + ':' +
                   f(this.getUTCMinutes())   + ':' +
                   f(this.getUTCSeconds())   + 'Z"';
    };


    Number.prototype.toJSONString = function () {
        return isFinite(this) ? String(this) : 'null';
    };


    Object.prototype.toJSONString = function (w) {
        var a = [],k,i,v;

        if (w) {
            for (i = 0; i < w.length; i += 1) {
                k = w[i];
                if (typeof k === 'string') {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':
                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString(w));
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());
                    }
                }
            }
        } else {
            for (k in this) {
                if (typeof k === 'string' &&
                        Object.prototype.hasOwnProperty.apply(this, [k])) {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':
                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString());
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());
                    }
                }
            }
        }
        return '{' + a.join(',') + '}';
    };


    (function (s) {
        var m = {'\b': '\\b','\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\'};
        s.parseJSON = function (filter) {
            var j;

            function walk(k, v) {
                var i, n;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                            n = walk(i, v[i]);
                            if (n !== undefined) {
                                v[i] = n;
                            } else {
                                delete v[i];
                            }
                        }
                    }
                }
                return filter(k, v);
            }
            if (/^[\],:{}\s]*$/.test(this.replace(/\\./g, '@').
                    replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
                    replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                j = eval('(' + this + ')');
                return typeof filter === 'function' ? walk('', j) : j;
            }
            throw new SyntaxError('parseJSON');
        };

        s.toJSONString = function () {
            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) +
                                               (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}

function yjjtestFn(a,b,c){
    var returnObj =window.showModalDialog("aaaa",null,'dialogWidth:400px;dialogHeight:300px;center:1;scroll:1;help:0;status:0');
    return {id:a,text:b,last:c};
}



//====================================================================================================
//扩展pageBar
//====================================================================================================

Ext.override(Ext.PagingToolbar,{
    onRender : function(ct, position){
        Ext.PagingToolbar.superclass.onRender.call(this, ct, position);
        
        //----------------------------------------------------------------
        //20080820 160400 于俊杰扩展
        //增加设置每页记录数的输入框及其回车响应
        //----------------------------------------------------------------
        this.addSeparator();
        this.add('每页');
        this.sizeField = Ext.get(this.addDom({
           tag: "input",
           type: "text",
           size: "3",
           value: this.pageSize,
           cls: "x-tbar-page-number"
        }).el);
        this.add('条');
        this.addSeparator();
        this.sizeField.on("keydown", this.onPageSizeKeydown, this);
        this.sizeField.on("focus", function(){this.dom.select();});
        this.sizeField.setHeight(18);
        //----------------------------------------------------------------
        //扩展结束
        //----------------------------------------------------------------
        
        this.first = this.addButton({
            tooltip: this.firstText,
            iconCls: "x-tbar-page-first",
            disabled: true,
            handler: this.onClick.createDelegate(this, ["first"])
        });
        this.prev = this.addButton({
            tooltip: this.prevText,
            iconCls: "x-tbar-page-prev",
            disabled: true,
            handler: this.onClick.createDelegate(this, ["prev"])
        });
        this.addSeparator();
        this.add(this.beforePageText);
        this.field = Ext.get(this.addDom({
           tag: "input",
           type: "text",
           size: "3",
           value: "1",
           cls: "x-tbar-page-number"
        }).el);
        this.field.on("keydown", this.onPagingKeydown, this);
        this.field.on("focus", function(){this.dom.select();});
        this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
        this.field.setHeight(18);
        this.addSeparator();
        this.next = this.addButton({
            tooltip: this.nextText,
            iconCls: "x-tbar-page-next",
            disabled: true,
            handler: this.onClick.createDelegate(this, ["next"])
        });
        this.last = this.addButton({
            tooltip: this.lastText,
            iconCls: "x-tbar-page-last",
            disabled: true,
            handler: this.onClick.createDelegate(this, ["last"])
        });
        this.addSeparator();
        this.loading = this.addButton({
            tooltip: this.refreshText,
            iconCls: "x-tbar-loading",
            handler: this.onClick.createDelegate(this, ["refresh"])
        });

        if(this.displayInfo){
            this.displayEl = Ext.fly(this.el.dom).createChild({cls:'x-paging-info'});
        }
        if(this.dsLoaded){
            this.onLoad.apply(this, this.dsLoaded);
        }
    },

    readPageSize : function(){
        var v = this.sizeField.dom.value, pageSize;
        if (!v || isNaN(pageSize = parseInt(v, 10))) {
            this.sizeField.dom.value = this.pageSize;
            return false;
        }
        return pageSize;
    },

    onLoad : function(store, r, o){
        if(!this.rendered){
            this.dsLoaded = [store, r, o];
            return;
        }
       this.cursor = o.params ? o.params[this.paramNames.start] : 0;
       var d = this.getPageData(), ap = d.activePage, ps = d.pages;

       this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
       this.field.dom.value = ap;
       this.first.setDisabled(ap == 1);
       this.prev.setDisabled(ap == 1);
       this.next.setDisabled(ap == ps);
       this.last.setDisabled(ap == ps);
       this.loading.enable();
       this.updateInfo();
    },

    updateInfo : function(){
        if(this.displayEl){
            var count = this.store.getCount();
            if(arguments.length==1) count = parseInt(arguments[0],10);
            var msg = count == 0 ?
                this.emptyMsg :
                String.format(
                    this.displayMsg,
                    this.cursor+1, this.cursor+count, this.store.getTotalCount()
                );
            this.displayEl.update(msg);
        }
    },
        
    onPageSizeKeydown : function(e){
        var k = e.getKey(), d = this.getPageData(), pageNum;
        if (k == e.RETURN) {
            //debugger;
            e.stopEvent();
            if(pageSize = this.readPageSize()){
                this.pageSize = pageSize;
                if(this.widget!=undefined){     //2009-06-27 增加，把pageSize传递到表格组件，以同步查询时的每页记录数
                    this.widget.pageSize = pageSize;
                }
            }

            this.cursor = 0;    //2008-09-09 于俊杰注释 修改每页记录数后，自动跳转到第一页
            this.doLoad(0);     //2008-09-09 于俊杰注释 修改每页记录数后，自动跳转到第一页
            
            // 2009-06-27 于俊杰修改，由原料二期最终版本复制而来
            //if(pageNum = this.readPage(d)){
            //    pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
            //    this.doLoad(pageNum * this.pageSize);
            //}
        }
    }
});


//====================================================================================================
//====================================================================================================
Ext.grid.RowNumberer = function(config){
    Ext.apply(this, config);
    if(this.rowspan){
        this.renderer = this.renderer.createDelegate(this);
    }
};

Ext.grid.RowNumberer.prototype = {
    header: "&nbsp;",
    width: 23,
    sortable: false,

    fixed:true,
    dataIndex: '',
    id: 'numberer',
    rowspan: undefined,

    renderer : function(v, p, record, rowIndex){
        //debugger;
        if(this.rowspan){
            p.cellAttr = 'rowspan="'+this.rowspan+'"';
        }
        return rowIndex+1;
    }
};

//====================================================================================================
//表头列合并、行合并
//====================================================================================================
Ext.namespace("Ext.ux.plugins");
Ext.ux.plugins.XGrid = function(config) {
	Ext.apply(this, config);
};
Ext.extend(Ext.ux.plugins.XGrid, Ext.util.Observable, {
    init: function(grid){
		this.grid = grid;
		this.view = this.grid.getView();
        this.view.layout = this.layout.createDelegate(this);
        this.grid.render = this.render.createDelegate(this);
        var cm = this.grid.getColumnModel();
        if(cm.headers) {
            this.initTemplates();
            this.initMethodDelegate();
            this.grid.on("columnresize", this.onColumnresize, this);
        }
 	},
    render : function(container, position){
        if(!this.grid.rendered && this.grid.fireEvent("beforerender", this) !== false){
            if((!container && this.grid.el) || typeof container == "string"){
                var elId = container ? container : this.grid.el;
                var c = document.getElementById(elId);
                if (!c.style.height) {
                    c.style.height = '100%';
                }
                this.grid.originWidth = c.offsetWidth;
                //this.grid.originHeight = c.offsetHeight;
                this.grid.originHeight = this.grid.height;//c.offsetHeight;  //update by yjj 2009-08-10
                
                this.grid.el = Ext.get(elId);
                container = this.grid.el.dom.parentNode;
                this.grid.allowDomMove = false;
            }
            this.grid.container = Ext.get(container);
            if(this.grid.ctCls){
                this.grid.container.addClass(this.grid.ctCls);
            }
            this.grid.rendered = true;
            if(position !== undefined){
                if(typeof position == 'number'){
                    position = this.grid.container.dom.childNodes[position];
                }else{
                    position = Ext.getDom(position);
                }
            }
            this.grid.onRender(this.grid.container, position || null);
            if(this.grid.autoShow){
                this.grid.el.removeClass(['x-hidden','x-hide-' + this.grid.hideMode]);
            }
            if(this.grid.cls){
                this.grid.el.addClass(this.grid.cls);
                delete this.grid.cls;
            }
            if(this.grid.style){
                this.grid.el.applyStyles(this.grid.style);
                delete this.grid.style;
            }
            this.grid.fireEvent("render", this);
            this.grid.afterRender(this.grid.container);
            if(this.grid.hidden){
                this.grid.hide();
            }
            if(this.grid.disabled){
                this.grid.disable();
            }

            this.grid.initStateEvents();
        }
        return this;
    },

    layout : function(){
        if(!this.view.mainBody){
            return; // not rendered
        }
        var g = this.view.grid;
        var c = g.getGridEl(), cm = this.view.cm,
                expandCol = g.autoExpandColumn,
                gv = this;
        if( Ext.isIE) {
            //c.setHeight(this.grid.originHeight);          //20090922 183000 取消该语句执行，因为长烟MES二期的BUG 
        }
        var csize = c.getSize(true);
        var vw = csize.width;

        if(vw < 20 || csize.height < 20){ // display: none?
            return;
        }

        if(g.autoHeight){
            this.view.scroller.dom.style.overflow = 'visible';
        }else{
            if( Ext.isIE) {
                this.view.el.setSize('100%', csize.height);
    
                var hdHeight = this.view.mainHd.getHeight();
                var vh = csize.height - (hdHeight);

    
                this.view.scroller.setSize('100%', vh);
                if(this.view.innerHd){
                    this.view.innerHd.style.width = '100%';
                }
            }    
            else {
                this.view.el.setSize(csize.width, csize.height);
    
                var hdHeight = this.view.mainHd.getHeight();
                var vh = csize.height - (hdHeight);
    
                this.view.scroller.setSize(vw, vh);
                if(this.view.innerHd){
                    this.view.innerHd.style.width = (vw)+'px';
                }
            }
        }
        if(this.view.forceFit){
            if(this.view.lastViewWidth != vw){
                this.view.fitColumns(false, false);
                this.view.lastViewWidth = vw;
            }
        }else {
            this.view.autoExpand();
        }
        this.view.onLayout(vw, vh);
    },
    initTemplates: function(){
        this.view.initTemplates.call(this);
        this.view.templates = {
            header : new Ext.Template(
                    '<table border="0" cellspacing="0" cellpadding="0" style="{tstyle};TABLE-LAYOUT: auto">',
                    '<thead>',
                    '{headers}',
                    '</thead>',
                    "</table>"
                    ),
            hcell : new Ext.Template(
                    '<td ',
                    '{rowspan}',
                    ' {colspan} ',
                    'class="x-grid3-hd x-grid3-cell x-grid3-td-{id}" ',
                    'style="{style}"><div {tooltip} {attr} ',
                    'class="x-grid3-hd-inner x-grid3-hd-{id}" ',
                    'unselectable="on" style="{istyle}">', 
                    this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '',
                    '{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />',
                    "</div></td>"
                    ),
            ghcell : new Ext.Template(
                    '<td ',
                    '{rowspan}',
                    ' {colspan} ',
                    'class="x-grid3-hd" ',
                    'style="border-bottom:1px solid #D0D0D0;{style}"><div {tooltip} {attr} ',
                    'class="x-grid3-hd-inner" ',
                    'unselectable="on" style="{istyle}">', 
                    this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '',
                    '{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />',
                    "</div></td>"
                    )

        };
    },
    
    initMethodDelegate: function() {
        var view = this.grid.getView();
        view.renderHeaders = this.renderHeaders.createDelegate(this);
        view.getColumnStyle = this.getColumnStyle.createDelegate(this);
        view.getHeaderCell = this.getHeaderCell.createDelegate(this);
        view.updateSortIcon = this.updateSortIcon.createDelegate(this);
        var cm = this.grid.getColumnModel();
        cm.moveColumn = this.moveColumn.createDelegate(this);
        
        //view.getColumnWidth = this.getColumnWidth.createDelegate(this);
        //view.getTotalWidth = this.getTotalWidth.createDelegate(this);
        
    },

    moveColumn : function(oldIndex, newIndex){
        var cm = this.grid.getColumnModel();
        var c = cm.config[oldIndex];
        if (this.realCM) {
            var rm1 = this.realCM[oldIndex];
            var rm2 = this.realCM[newIndex];
            if ( (!rm1.rowspan && !rm2.rowspan) || (rm1.rowspan == rm2.rowspan)) {
                cm.config.splice(oldIndex, 1);
                cm.config.splice(newIndex, 0, c);
                cm.dataMap = null;
                this.columnMoved = true;
                cm.fireEvent("columnmoved", cm, oldIndex, newIndex);
                this.columnMoved = false;
            }
        } else {
            cm.config.splice(oldIndex, 1);
            cm.config.splice(newIndex, 0, c);
            cm.dataMap = null;
            this.columnMoved = true;
            cm.fireEvent("columnmoved", cm, oldIndex, newIndex);
            this.columnMoved = false;
        }
    },
    
    renderHeaders : function(){
        //debugger;
        var cm = this.grid.getColumnModel();
        var hm = cm.headers;
        var ts = this.view.templates;
        var ct = ts.hcell;
        var tHeaderRow = new Ext.Template(
            '<tr class="x-grid3-hd-row">{cells}</tr>'
        );
        this.realCM = this.processRealColumnModel();

        //debugger;
        var  rs = [];
        
        var colIndex = 0;
        for(var k = 0; k < hm.length; k++) {
            var header = hm[k];
            var cb = [];
            for(var i = 0, len = header.length; i < len; i++){
                var p = {};
                var rm = header[i];
                p.id = rm.id ? rm.id : i;
                p.value = rm.header || "";
                //p.value = this.findHeaderFromConfig(rm.id, rm.header) || "";
                if(p.value==""&&i==0)
                    p.style ="width:22px;text-align:center;";
                else
                    p.style = rm.style || ""; // this.view.getColumnStyle(i, true, rm);
                //p.style = rm.style || ;
                p.tooltip = cm.getColumnTooltip(i);
                if (rm.rowspan) {
                    p.rowspan = 'rowspan=' + rm.rowspan;
                }
                if (rm.colspan && rm.colspan > 1) {
                    var colspan = rm.colspan;
                    var w = 0;
                    for (var c = 0; c < colspan; c++) {
                        var subCM = cm.config[colIndex+c];
                        if (subCM) {
                            w += cm.getColumnWidth(colIndex+c);
                        }
                    }
                    var style = '';
                    style += 'width:'+w+'px;';
                    if(cm.isHidden(i)){
                        style += 'display:none;';
                    }
                    var align = rm.align;
                    if(align){
                        style += 'text-align:'+align+';';
                    } else {
                        style += 'text-align:center;';
                    }
                    p.style = style;
                    p.colspan = 'colspan=' + rm.colspan;
                }
                
                if (rm.align == 'right'){
                    //p.istyle = 'padding-right:16px';
                } else {
                    delete p.istyle;
                }
                if (typeof(rm.id) != typeof(undef)) {
                    cb[cb.length] = ct.apply(p);
                    colIndex++ ;
                } else {
                    cb[cb.length] = ts.ghcell.apply(p);
                }
            }
            rs[rs.length] = tHeaderRow.apply({cells: cb.join("")});
        }

        //var data = ts.header.apply({headers:rs.join("")});
        var data = ts.header.apply({headers:rs.join(""), tstyle:'width:'+this.view.getTotalWidth()+';'});
        
        //document.getElementById("testdata").value=data;
        return data;
    },
    
    processRealColumnModel : function() {
        var cm = this.grid.getColumnModel();
        if (!cm.headers) {
            return cm.config;
        }
        var hm = cm.headers;
        var rows = hm.length;
        var realModels = [];
        var tmp = [];
        for (var i = 0; i < rows; i++) {
            tmp.push([]);
        }
        for (var k = 0; k < rows; k++) {
            var header = hm[k];
            for(var i = 0, len = header.length; i < len; i++){
                var p = header[i];
                
                var position = this.pushInto(tmp[k], p);
                
                if (p.rowspan && p.rowspan > 0) {
                    for (var r = 1; r < p.rowspan; r++) {
                        tmp[k + r][position] = p;
                    }
                }
                
                if (p.colspan && p.colspan > 0) {
                    for (var c = 0; c < p.colspan - 1; c++) {
                        position = this.pushInto(tmp[k], p);
                        if (p.rowspan && p.rowspan > 0) {
                            for (var r = 1; r < p.rowspan; r++) {
                                tmp[k + r][position] = p;
                            }
                        }
                    }
                }
            }
        }
        
        for (var i = 0; i < tmp[tmp.length-1].length; i++) {
            realModels.push(tmp[tmp.length-1][i]);
        }

        delete tmp;
        
        for(var i = 0, len = realModels.length; i < len; i++){
            var config = cm.config[i];
            rm = realModels[i];
            rm.style = this.getColumnStyle(i, true, rm);
            rm.id = config ? config.id : rm.id;
            if (config) {
                if (this.columnMoved) {
                    rm.header = config.header;
                } else {
                    config.header = rm.header;
                }

            }
        }
        return realModels;
    },
    
    pushInto : function(arrayObj, obj) {
        for (var i = 0; i < arrayObj.length; i++) {
            if (!arrayObj[i]) {
                arrayObj[i] = obj;
                return i;
            }
        }
        arrayObj.push(obj);
        return arrayObj.length - 1;
    },

    getColumnStyle : function(col, isHeader, realModel){
        var cm = this.grid.getColumnModel();
        var view = this.grid.getView();
        var style = !isHeader ? (cm.config[col].css || '') : '';
        if (Ext.isIE) {
            var w = cm.getColumnWidth(col);
            //w = isHeader ? w : w + 2;
            style += 'width:'+w+'px;';
        } else {
            style += 'width:'+this.view.getColumnWidth(col)+';';
        }
        if(cm.isHidden(col)){
            style += 'display:none;';
        }
        var align = cm.config[col].align;
        if (realModel && realModel.align) {
            align = realModel.align;
        }
        if (align) {
            style += 'text-align:'+align+';';
        } else {
            style += 'text-align:center;';
        }
        return style;
    },
    
    getHeaderCell : function(index){
        var view = this.grid.getView();
        var hds = view.mainHd.select('.x-grid3-cell');
        return (hds.item(index).dom);
    },
    
    updateSortIcon : function(col, dir){
        var sc = this.view.sortClasses;
        var hds = this.view.mainHd.select('.x-grid3-cell').removeClass(sc);
        hds.item(col).addClass(sc[dir == "DESC" ? 1 : 0]);
    },

    onColumnresize : function(col, width){
        var cm = this.grid.getColumnModel();
        this.grid.reconfigure(this.grid.store,cm);
    }
});

//====================================================================================================
//时间录入组件
//====================================================================================================
Ext.form.timeField = Ext.extend(Ext.form.TextField,  {
    fieldClass: "x-form-field x-form-num-field",
    allowDecimals : true,
    decimalSeparator : ":",
    decimalPrecision : 2,
    allowNegative : false,
    minValue : Number.NEGATIVE_INFINITY,
    maxValue : Number.MAX_VALUE,
    maxLength: 8,
    minText : "The minimum value for this field is {0}",
    maxText : "The maximum value for this field is {0}",
    nanText : "{0} is not a valid number",
    baseChars : "0123456789",

    // private
    initEvents : function(){
        Ext.form.NumberField.superclass.initEvents.call(this);
        var allowed = this.baseChars+'';
        if(this.allowDecimals){
            allowed += this.decimalSeparator;
        }
        if(this.allowNegative){
            allowed += "-";
        }
        //debugger;
        this.stripCharsRe = new RegExp('[^'+allowed+']', 'gi');
        var keyPress = function(e){
            var k = e.getKey();
            
            if(!Ext.isIE && (e.isSpecialKey() || k == e.BACKSPACE || k == e.DELETE)){
                return;
            }
            var c = e.getCharCode();
            if(allowed.indexOf(String.fromCharCode(c)) === -1){
                e.stopEvent();
            }
        };
        this.el.on("keypress", keyPress, this);
    },

    // private
    validateValue : function(value){

        if(value.length>6 && value.indexOf(":")==-1)
            value = value.left(6);

        //debugger;
        var updateFlag = false;
        
        if(!Ext.form.timeField.superclass.validateValue.call(this, value)){
            return false;
        }
        if(value.length < 1){ // if it's blank and textfield didn't flag it then it's valid
            return true;
            return (this.allowBlank===false)?false:true;
        }
        if(value.indexOf(":")==-1&&value.length==6){
            var vs =""+value;
            value = vs.substr(0,2)+":"+vs.substr(2,2)+":"+vs.substr(4,2);
            updateFlag = true;
        }
        if(!Sail.isTime(value)){
            this.el.addClass(this.invalidClass);
            return false;
        }
        if(updateFlag) this.setValue(value);
        return true;
    },

    getValue : function(){
        if(this.getMode==='hms'){
            var v = Ext.form.timeField.superclass.getValue.call(this);
            return v.replaceAll(":","");
        }else{
            var v = Ext.form.timeField.superclass.getValue.call(this);
            
            return this.parseValue(v);
        }
    },

    setValue : function(v){
        Ext.form.timeField.superclass.setValue.call(this, this.parseValue(v));
    },

    // private
    parseValue : function(value){
        if(value=="") return "";
        
        if(value.length>6 && value.indexOf(":")==-1)
            value = value.left(6);

        if(value.indexOf(":")==-1&&value.length==6){
            if(!Sail.isTime(value)) return "";
            var vs =""+value;
            return vs.substr(0,2)+":"+vs.substr(2,2)+":"+vs.substr(4,2);
        }
        
        
        var vs = value.split(":");
        if(vs.length==1){
            var vback = value;
            vs = [];

            var h = parseInt(vback.left(2),10)||0;
            vs.push((h>23)?vback.left(1):""+h);
            vback = ((h>23)?vback.right(vback.length-1):vback.right(vback.length-2))
            
            var h = parseInt(vback.left(2),10)||0;
            vs.push((h>59)?vback.left(1):""+h);
            vback = ((h>59)?vback.right(vback.length-1):vback.right(vback.length-2))
            
            vs.push((parseInt(vback,10)>59)?"0":vback);
        }
        

        
        for(var i=0;i<vs.length;i++){
            vs[i]=(vs[i]=="")?"00":vs[i];
            
            if(vs[i].length==1 && parseInt(vs[i],10)<10&&parseInt(vs[i],10)!=0){
                vs[i]="0"+vs[i];
            }
            if(vs[i]=="0") vs[i]="00";
        }
        return vs.join(":");
    },


    
    beforeBlur : function(){
        
        if(this.validateValue(this.getValue())==false){
            var v = (this.allowBlank===true)?"":"00:00:00";            
            this.setValue(v);
        }else
            this.setValue(this.parseValue(this.getRawValue()));
    }
});

Ext.reg('timeField', Ext.form.timeField);


//====================================================================================================
//====================================================================================================

Ext.override(Ext.form.Field,{
    onFocus : function(){
        //debugger;    
        if(!Ext.isOpera && this.focusClass){ // don't touch in Opera
            this.el.addClass(this.focusClass);
        }
        if(!this.hasFocus){
            this.hasFocus = true;
            this.startValue = this.getValue();
            this.fireEvent("focus", this);
        }
    },
    onBlur : function(){
        //debugger;
        this.beforeBlur();
        if(!Ext.isOpera && this.focusClass){             this.el.removeClass(this.focusClass);
        }
        this.hasFocus = false;
        if(this.validationEvent !== false && this.validateOnBlur && this.validationEvent != "blur"){
            this.validate();
        }
        var v = this.getValue();
        if(String(v) !== String(this.startValue)){
            this.fireEvent('change', this, v, this.startValue);
        }
        this.fireEvent("blur", this);
    },
    markInvalid : function(msg){
        if(!this.rendered || this.preventMark){ // not rendered
            return;
        }
        this.el.addClass(this.invalidClass);
        msg = msg || this.invalidText;
        switch(this.msgTarget){
            case 'qtip':
                this.el.dom.qtip = msg;
                //this.el.dom.qclass = 'x-form-invalid-tip';
                if(Ext.QuickTips){ // fix for floating editors interacting with DND
                    Ext.QuickTips.enable();
                }
                break;
            case 'title':
                this.el.dom.title = msg;
                break;
            case 'under':
                if(!this.errorEl){
                    var elp = this.el.findParent('.x-form-element', 5, true);
                    this.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
                    this.errorEl.setWidth(elp.getWidth(true)-20);
                }
                this.errorEl.update(msg);
                Ext.form.Field.msgFx[this.msgFx].show(this.errorEl, this);
                break;
            case 'side':
                if(!this.errorIcon){
                    //Debugger;
                    var elp = Ext.get(this.el.dom.parentElement);
                    //var elp = this.el.findParent('.x-form-element', 5, true);
                    this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
                }
                this.alignErrorIcon();
                this.errorIcon.dom.qtip = msg;
                //this.errorIcon.dom.qclass = 'x-form-invalid-tip';
                this.errorIcon.show();
                this.on('resize', this.alignErrorIcon, this);
                break;
            default:
                var t = Ext.getDom(this.msgTarget);
                t.innerHTML = msg;
                t.style.display = this.msgDisplay;
                break;
        }
        this.fireEvent('invalid', this, msg);
    }    
});


//====================================================================================================
//add aftersetvalue event
//====================================================================================================
Ext.override(Ext.form.DateField,{
    initComponent : function(){
        Ext.form.DateField.superclass.initComponent.call(this);
        if(typeof this.minValue == "string"){
            this.minValue = this.parseDate(this.minValue);
        }
        if(typeof this.maxValue == "string"){
            this.maxValue = this.parseDate(this.maxValue);
        }
        this.ddMatch = null;
        if(this.disabledDates){
            var dd = this.disabledDates;
            var re = "(?:";
            for(var i = 0; i < dd.length; i++){
                re += dd[i];
                if(i != dd.length-1) re += "|";
            }
            this.ddMatch = new RegExp(re + ")");
        }
        
        this.addEvents("beforeclick","aftersetvalue");
        
    },
    beforeBlur : function(){
        var v = this.parseDate(this.getRawValue());
        if(v){
            this.setValue(v,'blur');
        }
    },    
    onTriggerClick : function(){
        if(this.disabled){
            return;
        }

        var flag = this.fireEvent("beforeclick", this,this);
        
        if(!flag) {
            this.keyFireEvent = false;
            return;
        }
        
        
        if(this.menu == null){
            this.menu = new Ext.menu.DateMenu();
        }
        Ext.apply(this.menu.picker,  {
            minDate : this.minValue,
            maxDate : this.maxValue,
            disabledDatesRE : this.ddMatch,
            disabledDatesText : this.disabledDatesText,
            disabledDays : this.disabledDays,
            disabledDaysText : this.disabledDaysText,
            format : this.format,
            minText : String.format(this.minText, this.formatDate(this.minValue)),
            maxText : String.format(this.maxText, this.formatDate(this.maxValue))
        });
        this.menu.on(Ext.apply({}, this.menuListeners, {
            scope:this
        }));
        this.menu.picker.setValue(this.getValue() || new Date());
        this.menu.show(this.el, "tl-bl?");
    },
   
    setValue : function(date,mode){
        this.originalValue = (this.getValue()=='')?'':this.getValue().format('Ymd');
        Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
        var newValue = (this.getValue()=='')?'':this.getValue().format('Ymd');
        
        if(mode==undefined)
            var flag = this.fireEvent("aftersetvalue", this,this.originalValue,newValue);
    }
    
});


//====================================================================================================
//====================================================================================================
Ext.override(Ext.DatePicker,{
    onRender : function(container, position){
        var m = [
             '<table cellspacing="0">',
                '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'">&#160;</a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'">&#160;</a></td></tr>',
                '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'];
        var dn = this.dayNames;
        for(var i = 0; i < 7; i++){
            var d = this.startDay+i;
            if(d > 6){
                d = d-7;
            }
            m.push("<th><span>", dn[d].substr(0,1), "</span></th>");
        }
        m[m.length] = "</tr></thead><tbody><tr>";
        for(var i = 0; i < 42; i++) {
            if(i % 7 == 0 && i != 0){
                m[m.length] = "</tr><tr>";
            }
            m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
        }
        m[m.length] = '</tr></tbody></table></td></tr><tr><td colspan="3" class="x-date-bottom" align="center"></td></tr></table><div class="x-date-mp"></div>';

        var el = document.createElement("div");
        el.className = "x-date-picker";
        el.innerHTML = m.join("");

        container.dom.insertBefore(el, position);

        this.el = Ext.get(el);
        this.eventEl = Ext.get(el.firstChild);

        new Ext.util.ClickRepeater(this.el.child("td.x-date-left a"), {
            handler: this.showPrevMonth,
            scope: this,
            preventDefault:true,
            stopDefault:true
        });

        new Ext.util.ClickRepeater(this.el.child("td.x-date-right a"), {
            handler: this.showNextMonth,
            scope: this,
            preventDefault:true,
            stopDefault:true
        });

        this.eventEl.on("mousewheel", this.handleMouseWheel,  this);

        this.monthPicker = this.el.down('div.x-date-mp');
        this.monthPicker.enableDisplayMode('block');
        
        var kn = new Ext.KeyNav(this.eventEl, {
            "left" : function(e){
                e.ctrlKey ?
                    this.showPrevMonth() :
                    this.update(this.activeDate.add("d", -1));
            },

            "right" : function(e){
                e.ctrlKey ?
                    this.showNextMonth() :
                    this.update(this.activeDate.add("d", 1));
            },

            "up" : function(e){
                e.ctrlKey ?
                    this.showNextYear() :
                    this.update(this.activeDate.add("d", -7));
            },

            "down" : function(e){
                e.ctrlKey ?
                    this.showPrevYear() :
                    this.update(this.activeDate.add("d", 7));
            },

            "pageUp" : function(e){
                this.showNextMonth();
            },

            "pageDown" : function(e){
                this.showPrevMonth();
            },

            "enter" : function(e){
                e.stopPropagation();
                return true;
            },

            scope : this
        });

        this.eventEl.on("click", this.handleDateClick,  this, {delegate: "a.x-date-date"});

        this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday,  this);

        this.el.unselectable();
        
        this.cells = this.el.select("table.x-date-inner tbody td");
        this.textNodes = this.el.query("table.x-date-inner tbody span");

        this.mbtn = new Ext.Button({
            text: "&#160;",
            tooltip: this.monthYearText,
            renderTo: this.el.child("td.x-date-middle", true)
        });

        this.mbtn.on('click', this.showMonthPicker, this);
        this.mbtn.el.child(this.mbtn.menuClassTarget).addClass("x-btn-with-menu");

        var today = (new Date()).dateFormat(this.format);
        var todayBtn = new Ext.Button({
            //renderTo: this.el.child("td.x-date-bottom", true),    //2009-06-29 yjj update
            text: String.format(this.todayText, today),
            tooltip: String.format(this.todayTip, today),
            handler: this.selectToday,
            scope: this
        });
        
        //-------------------------------------------------------------------------------
        //add begin 2009-06-29 by yjj
        //add a button for clear date
        //-------------------------------------------------------------------------------
        var clearBtn = new Ext.Button({
            //renderTo: this.el.child("td.x-date-bottom", true),
            text: '清除',
            tooltip: String.format(this.todayTip, today),
            handler: this.clearDate,
            scope: this
        });

        
        this.buttons = [];
        this.buttons.push(todayBtn);
        this.buttons.push(clearBtn);
        
        var op = Ext.get(this.el.child("td.x-date-bottom", true));

        var tb = op.createChild({cls:'x-panel-btns-ct', cn: {
            cls:"x-panel-btns x-panel-btns-center",
            html:'<table cellspacing="0"><tbody><tr></tr></tbody></table><div class="x-clear"></div>'
        }}, null, true);
        var tr = tb.getElementsByTagName('tr')[0];
        for(var i = 0, len = this.buttons.length; i < len; i++) {
            var b = this.buttons[i];
            var td = document.createElement('td');
            td.className = 'x-panel-btn-td';
            b.render(tr.appendChild(td));
        }
        //-------------------------------------------------------------------------------
        //add over 2009-06-29 by yjj
        //-------------------------------------------------------------------------------
        


        if(Ext.isIE){
            this.el.repaint();
        }
        this.update(this.value);
    },
    clearDate : function(){
        this.fireEvent("select", this, '');
    }    
});


//====================================================================================================
//====================================================================================================
Ext.form.SelectField = Ext.extend(Ext.form.TriggerField,  {
    
    readOnly : false,
    minValue : null,
    maxValue : null,
    invalidText : "{0} is not a valid date - it must be in the format {1}",
    triggerClass : 'x-form-select-trigger',
    defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
    //defaultAutoCreate : {tag: "textarea", style:"height:50",  type: "text", size: "10", autocomplete: "off"},
    showValue : "text",
    dataValue : "id",

    otherFields : [],
    
    openUrl : "",
    dataObj : {},

    onHide : function(){
        //debugger;
        this.wrap.dom.style.display = 'none';
    },
    
    initComponent : function(){
        Ext.form.SelectField.superclass.initComponent.call(this);

        this.addEvents("beforeclick");
        this.addEvents("datachange");
        this.addEvents("afterclick");
        
        if(this.useTextArea===true) {
            if(this.textAreaHeight!=undefined){
                this.defaultAutoCreate = {tag: "textarea", style:"height:"+this.textAreaHeight,  type: "text", size: "10", autocomplete: "off"};
            }
        }

        this.initDataObj();
    },
    
    initDataObj : function(){
        this.idField    = this.idField ||"id";
        this.textField  = this.textField ||"text";
        this.valueField = this.valueField ||"value";
        
        this.dataObj = {};
        this.dataObj[this.idField]   ="";
        this.dataObj[this.textField] ="";
        this.dataObj[this.valueField]="";
        
        if(this.otherFields.length>0){
            for(var i=0;i<this.otherFields.length;i++){
                this.dataObj[this.otherFields[i]]="";
            }
        }
    },
    
    initEvents : function(){    
        this.el.on("keypress", this.myKeyFn,  this);
        this.el.on("focus", this.onFocus,  this);
        //20080812威威发现加次定义后，点击...按钮不会弹出窗口啦
        //原因分析结果是：加了blur事件后，导致真个组件失去焦点，因此无法响应...按钮的点击事件
        //this.el.on("blur", this.triggerBlur,  this);      
        
        
    },
    
    myKeyFn : function(e){
        var k = e.getKey();
        if(!Ext.isIE && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
            return;
        }
        
        if(k==e.ENTER){
            this.inputText = this.el.dom.value;
            this.keyFireEvent = true;
            this.onTriggerClick();
        }
    },
    // private
    validateValue : function(value){
        if(!Ext.form.SelectField.superclass.validateValue.call(this, value)){
            return false;
        }
        return true;
    },

    validateBlur : function(){
        return !this.menu || !this.menu.isVisible();
    },

    getValue : function(){
        //return this.getDataObj((this.value)?this.value:"id");
        return Ext.form.SelectField.superclass.getValue.call(this) || "";
    },

    getText : function(){
        return this.getDataObj((this.text)?this.text:"text");    
    },
    setValue : function(date){
        //debugger;
        Ext.form.SelectField.superclass.setValue.call(this, date);
        if(date=="") this.clearDataObj();       //值为空，默认行为，清除dataObj
        var flag = this.fireEvent("datachange", this,this);

        //var flag = this.fireEvent("afterclick", this,this,this.dataObj);
    },

    // private
    onDestroy : function(){
        if(this.wrap){
            this.wrap.remove();
        }
        Ext.form.SelectField.superclass.onDestroy.call(this);
    },

    onTriggerClick : function(){
        if(this.disabled){
            return;
        }
        var flag = this.fireEvent("beforeclick", this,this);
        
        if(!flag) {
            this.keyFireEvent = false;
            return;
        }
        
        this.onFocus();
        if(!this.openUrl || this.openUrl=="") {
            if(this.openFn && this.openFn!=""){
                eval("var returnObj = "+this.openFn);
                //debugger;
                if(returnObj){
                    this.dataObj = {};
                    Ext.apply(this.dataObj,returnObj);
                    this.setValue((returnObj[this.showValue])?returnObj[this.showValue]:"");
                    var flag = this.fireEvent("afterclick", this.dataObj);
                }
            }
            else{
                var flag = this.fireEvent("afterclick", this.dataObj);
                this.keyFireEvent = false;
                return;
            }
            
        }else{
            
            var sData = this.dataObj;//{inputText:this.inputText};
            if(this.commonParameter){
                Sail.applyExFunc(sData,this.commonParameter);
            }
            //debugger;
            
            var w=(this.openWidth)?this.openWidth:400;
            var h=(this.openHeight)?this.openHeight:300;
            //debugger;
            var returnObj =window.showModalDialog(this.openUrl,sData,'dialogWidth:'+w+'px;dialogHeight:'+h+'px;center:1;scroll:1;help:0;status:0');
    
            if(returnObj){
                //debugger;
                Ext.apply(this.dataObj,returnObj);

                this.setValue((returnObj[this.showValue])?returnObj[this.showValue]:"");
                
                if(this.advanced){
                    this.setAdvanced(returnObj[this.dataValue]?returnObj[this.dataValue]:'');
                }
                var flag = this.fireEvent("afterclick", this,this.dataObj);
            }
        }
        this.keyFireEvent = false;
    },
    setDataObj : function(d){
        //debugger;
        //this.dataObj = {};
        Ext.apply(this.dataObj,d);
    },
    getDataObj : function(){
        return this.dataObj;
    },
    
   
    getIDValue : function(){
        return this.dataObj[(this.idField?this.idField:"id")];
    },

    getCodeValue : function(){
        return this.dataObj[(this.codeField?this.codeField:"value")];
    },

    clearDataObj : function(){
        for(var p in this.dataObj){
            //debugger;
            if(typeof this.dataObj[p] =='function'){
                continue;
            }else
                this.dataObj[p]="";
        }
        //this.dataObj={};
    },
    setNull : function(){
        this.openFn  ="";
        this.openUrl = "";
        this.dataObj = {};
        this.setValue("");
    },
    afterTriggerClick : function(){
    }

});
Ext.reg('selectfield', Ext.form.SelectField);


//====================================================================================================
//====================================================================================================
Ext.form.SelectFieldAdvanced = Ext.extend(Ext.form.SelectField,  {
    
    readOnly : false,
    minValue : null,
    maxValue : null,
    invalidText : "{0} is not a valid date - it must be in the format {1}",
    triggerClass : 'x-form-select-trigger',
    defaultAutoCreate : {tag: "input", type: "text", width:130,size: "4", autocomplete: "off"},
    showValue : "",
    
    openUrl : "",
    dataObj : {},
    nameWidth : 100,
    nameFlag : true,
    codeFlag : true,
    
    initComponent : function(){
        //debugger;
        Ext.form.SelectFieldAdvanced.superclass.initComponent.call(this);

        this.addEvents("beforeclick");
        this.addEvents("datachange");
        this.addEvents("afterclick");
        
    },
    initEvents : function(){    
        this.el.on("keypress", this.myKeyFn,  this);
        this.el.on("focus", this.onFocus,  this);
        this.el.on("blur", this.triggerBlur,  this);
    },
    
    onResize : function(w, h){
        
        //debugger;
        Ext.form.TriggerField.superclass.onResize.call(this, w, h);
        if(typeof w == 'number'){
            this.advanced.setWidth(250);
            this.el.setWidth(this.adjustWidth('input', w - 4-this.trigger.getWidth()-this.advanced.getWidth()));
            //this.el.setWidth(this.adjustWidth('input', w - this.trigger.getWidth()-this.advanced.getWidth()));
        }
        this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()+this.advanced.getWidth()+4);
    },
    hideName : function(){
        this.advanced.setDisplayed(false);
        this.nameFlag = false;
        if(!this.codeFlag)  this.space1.setWidth(39);
    },
    showName : function(){
        this.advanced.setDisplayed(true);
        this.nameFlag = true;
        this.space1.setWidth(2);
    },
    hideCode : function(){
        this.el.setDisplayed(false);
        this.codeFlag = false;
        if(!this.nameFlag)  this.space1.setWidth(39);
    },
    showCode : function(){
        this.el.setDisplayed(true);
        this.codeFlag = true;
        this.space1.setWidth(2);
    },
    hideAll: function(){
        this.hideCode();
        this.hideName();
    },
    showAll: function(){
        this.showCode();
        this.showName();
    },
    
    
    setAdvanced : function(value){
        this.advanced.dom.value = value;
    },
    getAdvanced : function(){
        return this.advanced.dom.value;
    },
    
    onRender : function(ct, position){
        Ext.form.TriggerField.superclass.onRender.call(this, ct, position);
        //debugger;
        this.wrap = this.el.wrap({cls: "x-form-field-wrap"});
        
        this.space1 = this.wrap.createChild({tag: "input", readonly:true,type:'text',style:'width:2;border:none;',cls: ""});
        this.trigger = this.wrap.createChild(this.triggerConfig ||
                {tag: "input", type:'button',style:'width:17;',cls: "x-form-text x-form-field x-form-sa"});
        if(this.hideTrigger){
            this.trigger.setDisplayed(false);
        }
            
        this.space2 = this.wrap.createChild({tag: "input", readonly:true,type:'text',style:'width:2;border:none;',cls: ""});
        this.advanced = this.wrap.createChild(this.advancedConfig || 
            {tag: "input", type:'text', readonly:true,size:10, cls: "x-form-text x-form-field ", autocomplete: "off"});
        
        this.initTrigger();
        if(!this.width){
            this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth()+this.advanced.getWidth());
        }
    }
});
Ext.reg('selectfieldadvanced', Ext.form.SelectFieldAdvanced);

//====================================================================================================
//====================================================================================================
Ext.grid.RadioSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, {
    header: '<div class="x-grid3-hd-radio">&#160;</div>',
    width: 20,
    sortable: false,

    fixed:true,
    dataIndex: '',
    id: 'checker',

    initEvents : function(){
        Ext.grid.RadioSelectionModel.superclass.initEvents.call(this);
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
            Ext.fly(view.innerHd).on('mousedown', this.onHdMouseDown, this);

        }, this);
    },

    // private
    onMouseDown : function(e, t){
        if(t.className == 'x-grid3-row-radio'){
            e.stopEvent();
            var row = e.getTarget('.x-grid3-row');
            if(row){
                var index = row.rowIndex;
                if(this.isSelected(index)){
                    this.deselectRow(index);
                }else{
                    this.selectRow(index, true);
                }
            }
        }
    },

    // private
    onHdMouseDown : function(e, t){
        if(t.className == 'x-grid3-hd-radio'){
            e.stopEvent();
            var hd = Ext.fly(t.parentNode);
            var isChecked = hd.hasClass('x-grid3-hd-radio-on');
            if(isChecked){
                hd.removeClass('x-grid3-hd-radio-on');
                this.clearSelections();
            }else{
                hd.addClass('x-grid3-hd-radio-on');
                this.selectAll();
            }
        }
    },

    // private
    renderer : function(v, p, record){
        return '<div class="x-grid3-row-radio">&#160;</div>';
    }
});


Ext.override(Ext.data.Connection,{
    timeout : 60000
});
Ext.override(Ext.form.ComboBox,{
    maxHeight:200
});

//=======================================================================================================
//=======================================================================================================
Ext.override(Ext.form.ComboBox,{
    initComponent : function(){
        Ext.form.ComboBox.superclass.initComponent.call(this);
        this.addEvents('beforeclick','expand','collapse','beforeselect','select','beforequery','aftersetvalue');
        if(this.transform){
            this.allowDomMove = false;
            var s = Ext.getDom(this.transform);
            if(!this.hiddenName){
                this.hiddenName = s.name;
            }
            if(!this.store){
                this.mode = 'local';
                var d = [], opts = s.options;
                for(var i = 0, len = opts.length;i < len; i++){
                    var o = opts[i];
                    var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
                    if(o.selected) {this.value = value;}
                    d.push([value, o.text]);
                }
                this.store = new Ext.data.SimpleStore({'id': 0,fields: ['value', 'text'],data : d});
                this.valueField = 'value';
                this.displayField = 'text';
            }
            s.name = Ext.id();             if(!this.lazyRender){
                this.target = true;
                this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
                Ext.removeNode(s);                 this.render(this.el.parentNode);
            }else{
                Ext.removeNode(s);             
            }
        }
        this.selectedIndex = -1;
        if(this.mode == 'local'){
            if(this.initialConfig.queryDelay === undefined){
                this.queryDelay = 10;
            }
            if(this.initialConfig.minChars === undefined){
                this.minChars = 0;
            }
        }
    },
    setValue : function(v){
        //debugger;
        var text = ((typeof v)=='object')?v.t:v;
        v = ((typeof v)=='object')?v.v:v;
        var r = {};
        //debugger;
        if(this.valueField){
            r = this.findRecord(this.valueField, v);
            if(r!=undefined){
                text = r.data[this.displayField];
            }else if(this.valueNotFoundText !== undefined){
                text = this.valueNotFoundText;
            }else{
                //v="";
                //text = "未选择...";
            }
        }
        this.lastSelectionText = text;
        if(this.hiddenField){
            this.hiddenField.value = v;
        }
        Ext.form.ComboBox.superclass.setValue.call(this, text);
        this.value = v;
        this.fireEvent('aftersetvalue', this, r,text,v);
        
    },
    onTriggerClick : function(){
        if(this.disabled){
            return;
        }

        var flag = this.fireEvent("beforeclick", this,this);
        if(!flag) return;

        if(this.isExpanded()){
            this.collapse();
            this.el.focus();
        }else {
            this.onFocus({});
            if(this.triggerAction == 'all') {
                this.doQuery(this.allQuery, true);
            } else {
                this.doQuery(this.getRawValue());
            }
            this.el.focus();
        }
    }   
    
});


Ext.override(Ext.grid.RowSelectionModel,{

    initEvents : function(){
        if(!this.grid.enableDragDrop && !this.grid.enableDrag){
            this.grid.on("rowmousedown", this.handleMouseDown, this);
        }else{ // allow click to work like normal
            this.grid.on("rowclick", function(grid, rowIndex, e) {
                if(e.button === 0 && !e.shiftKey && !e.ctrlKey) {
                    this.selectRow(rowIndex, false);
                    grid.view.focusRow(rowIndex);
                }
            }, this);
        }

        this.rowNav = new Ext.KeyNav(this.grid.getGridEl(), {
            "up" : function(e){
                if(!e.shiftKey){
                    this.selectPrevious(e.shiftKey);
                }else if(this.last !== false && this.lastActive !== false){
                    var last = this.last;
                    this.selectRange(this.last,  this.lastActive-1);
                    this.grid.getView().focusRow(this.lastActive);
                    if(last !== false){
                        this.last = last;
                    }
                }else{
                    this.selectFirstRow();
                }
            },
            "down" : function(e){
                if(!e.shiftKey){
                    this.selectNext(e.shiftKey);
                }else if(this.last !== false && this.lastActive !== false){
                    var last = this.last;
                    this.selectRange(this.last,  this.lastActive+1);
                    this.grid.getView().focusRow(this.lastActive);
                    if(last !== false){
                        this.last = last;
                    }
                }else{
                    this.selectFirstRow();
                }
            },
            scope: this
        });

        var view = this.grid.view;
        view.on("refresh", this.onRefresh, this);
        view.on("rowupdated", this.onRowUpdated, this);
        view.on("rowremoved", this.onRemove, this);
    },

    handleMouseDown : function(g, rowIndex, e){
        //debugger;
        if(e.button !== 0 || this.isLocked()){
            return;
        };
        var view = this.grid.getView();
        if(e.shiftKey && this.last !== false){
            var last = this.last;
            this.selectRange(last, rowIndex, e.ctrlKey);
            this.last = last; // reset the last
            view.focusRow(rowIndex);
        }else{
            var isSelected = this.isSelected(rowIndex);
            if(e.ctrlKey && isSelected){
                this.deselectRow(rowIndex);
            }else if(!isSelected || this.getCount() > 1){
                //=========================================================
                //2009-05-15 22:53 yjj update...
                //=========================================================
                //this.selectRow(rowIndex, e.ctrlKey || e.shiftKey);        //old code
                
                
                
                var cell = view.findCellIndex(e.getTarget());
                //debugger;
                if(cell!=undefined && cell!==false && cell!==true)
                    this.selectRow(rowIndex, e.ctrlKey || e.shiftKey,null,null,cell);
                else
                    this.selectRow(rowIndex, e.ctrlKey || e.shiftKey);
                //=========================================================
                //over
                //=========================================================

                view.focusRow(rowIndex);
            }
        }
    },
    
    //selectRow : function(index, keepExisting, preventViewNotify,stopEvent){       //old code
    selectRow : function(index, keepExisting, preventViewNotify,stopEvent,cell){    //new code add argument:cell
        if(this.locked || (index < 0 || index >= this.grid.store.getCount())) return;
        var r = this.grid.store.getAt(index);
        if(r && this.fireEvent("beforerowselect", this, index, keepExisting, r) !== false){
            if(!keepExisting || this.singleSelect){
                this.clearSelections();
            }
            this.selections.add(r);
            this.last = this.lastActive = index;
            if(!preventViewNotify){
                this.grid.getView().onRowSelect(index);
            }
            if(!stopEvent){
                //debugger;
                this.fireEvent("rowselect", this, index, r);
                //debugger;
                if(cell!=undefined && this.grid.getXType()!=="editorgrid"){     //add est. for focus blur when editorgrid 20090527 yjj
                    this.grid.fireEvent("cellclick", this.grid, index, cell,{});    //add code for cellclick e={}
                }
                this.fireEvent("selectionchange", this);
            }
        }
    },
    deselectRow : function(index, preventViewNotify){
        if(this.locked) return;
        if(this.last == index){
            this.last = false;
        }
        if(this.lastActive == index){
            this.lastActive = false;
        }
        var r = this.grid.store.getAt(index);
        if(r){
            this.selections.remove(r);
            if(!preventViewNotify){
                this.grid.getView().onRowDeselect(index);
            }
            this.fireEvent("rowdeselect", this, index, r);
            this.fireEvent("selectionchange", this);
        }
    }
});


Ext.override(Ext.grid.CheckboxSelectionModel,{
    onMouseDown : function(e, t){
        //debugger;
        
        if(t.className == 'x-grid3-row-checker'){
            e.stopEvent();
            var row = e.getTarget('.x-grid3-row');
            if(row){
                var index = row.rowIndex;
                if(this.isSelected(index)){
                    this.deselectRow(index);
                }else{
                    var cell = this.grid.view.findCellIndex(e.getTarget());
                    //===================================================================
                    //2009-05-16 22:18 add by yujunjie for cellclick fire
                    //===================================================================
                    //this.selectRow(index, true);              //old code
                    this.selectRow(index, true,null,null,cell); //new code. add argument cell 
                }
            }
        }
    }
});

//=======================================================================================================
//=======================================================================================================
Ext.override(Ext.grid.EditorGridPanel,{
    startEditing : function(row, col){
        //if(sc.isView()) return;
        //debugger;
        this.stopEditing();
        if(this.colModel.isCellEditable(col, row)){
            this.view.ensureVisible(row, col, true);
            var r = this.store.getAt(row);
            var field = this.colModel.getDataIndex(col);
            var e = {
                grid: this,
                record: r,
                field: field,
                value: r.data[field],
                row: row,
                column: col,
                cancel:false
            };
            if(this.fireEvent("beforeedit", e) !== false && !e.cancel){
                this.editing = true;
                var ed = this.colModel.getCellEditor(col, row);
                if(!ed.rendered){
                    ed.render(this.view.getEditorParent(ed));
                }
                (function(){ // complex but required for focus issues in safari, ie and opera
                    ed.row = row;
                    ed.col = col;
                    ed.record = r;
                    ed.field.lastQuery = undefined;         //扩展
                    
                    ed.on("complete", this.onEditComplete, this, {single: true});
                    ed.on("specialkey", this.selModel.onEditorKey, this.selModel);
                    this.activeEditor = ed;
                    var v = r.data[field];

                    var _type=ed.field.getXType();
                    var _text = null;
                    if(_type=='combo'){
                        var nameIndex = e.grid.colModel.config[col].nameIndex;
                        if(nameIndex){
                            _text = r.data[nameIndex];
                        }
                    }

                    if(_text!=null){
                        var o = {v:v,t:_text};
                        ed.startEdit(this.view.getCell(row, col), o);
                    }
                    else
                        ed.startEdit(this.view.getCell(row, col), v);
                }).defer(10, this);
            }
        }
    }
});

Ext.override(Ext.Editor,{
    startEdit : function(el, value){
        //debugger;
        
        if(this.editing){
            this.completeEdit();
        }
        this.boundEl = Ext.get(el);

        if((typeof value)=='object'){           //扩展
            var v = value.v !== undefined ? value.v : this.boundEl.dom.innerHTML;
        }else
            var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
            
            
        if(!this.rendered){
            this.render(this.parentEl || document.body);
        }
        if(this.fireEvent("beforestartedit", this, this.boundEl, v) === false){
            return;
        }
        this.startValue = v;
        
        if((typeof value)=='object'){           //扩展
            this.field.setValue(value);
        }else{
            this.field.setValue(v);
        }
        
        if(this.autoSize){
            var sz = this.boundEl.getSize();
            switch(this.autoSize){
                case "width":
                this.setSize(sz.width,  "");
                break;
                case "height":
                this.setSize("",  sz.height);
                break;
                default:
                this.setSize(sz.width,  sz.height);
            }
        }
        this.el.alignTo(this.boundEl, this.alignment);
        this.editing = true;
        this.show();
    },
    completeEdit : function(remainVisible){
        //debugger;
        if(!this.editing){
            return;
        }
        var v = this.getValue();
        if(this.revertInvalid !== false && !this.field.isValid()){
            v = this.startValue;
            this.cancelEdit(true);
        }
        if(String(v) === String(this.startValue) && this.ignoreNoChange){
            this.editing = false;
            this.hide();
            return;
        }
        if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
            this.editing = false;
            if(this.updateEl && this.boundEl){
                this.boundEl.update(v);
            }
            if(remainVisible !== true){
                this.hide();
            }
            this.fireEvent("complete", this, v, this.startValue);
        }
    },
    
    onShow : function(){

        this.el.show();
        if(this.hideEl !== false){
            this.boundEl.hide();
        }
        this.field.show();
        if(Ext.isIE && !this.fixIEFocus){ // IE has problems with focusing the first time
            this.fixIEFocus = true;
            this.deferredFocus.defer(10, this);
        }else{
            this.field.focus();

            var xtype = this.field.getXType();
            if(xtype=='combo' || xtype=='datefield' )
                this.field.onTriggerClick();
            
        }
        this.fireEvent("startedit", this.boundEl, this.startValue);
    },
    deferredFocus : function(){
        if(this.editing){
            this.field.focus();

            var xtype = this.field.getXType();
            if(xtype=='combo' || xtype=='datefield' )
                this.field.onTriggerClick();
        }
    },
    onHide : function(){
        //debugger;
        if(this.editing){
            this.completeEdit();
            return;
        }
        this.field.blur();
        if(this.field.collapse){
            this.field.collapse();
        }
        this.el.hide();
        if(this.hideEl !== false){
            this.boundEl.show();
        }
    }
    
});


Ext.override(Ext.grid.RowSelectionModel,{
    getLastSelected : function(){
        return this.selections.itemAt(this.selections.items.length-1);
    }
});

Ext.override(Ext.data.Record,{
    get : function(name){
        if(name.indexOf(".")!=-1)
            return this.data[name.replaceAll(".","__")];
        else
            return this.data[name]; 
    },
    set : function(name, value){
        if(String(this.data[name]) == String(value)){
            return;
        }
        this.dirty = true;
        if(!this.modified){
            this.modified = {};
        }
        if(typeof this.modified[name] == 'undefined'){
            this.modified[name] = this.data[name];
        }
        this.data[name] = value;
        if(!this.editing){
            this.store.afterEdit(this);
        }       
    }
});

//-----------------------------------------------------------------------------------
//重载方法：Ext.grid.GridView.renderHeaders
//重载目的：解决单选多选时，标题头check、radio图标重叠的问题
//备    注：通过扩展 RadioSelectionModel类，按照checkBoxSelectionModel解决思路
//          未达到预期效果，表格数据行实现radio，标题头出现重叠
//          暂时用此方法临时解决之   
//-----------------------------------------------------------------------------------
Ext.override(Ext.grid.GridView,{
    renderHeaders : function(){
	    var cm = this.cm, ts = this.templates;
        var ct = ts.hcell;

        var cb = [], sb = [], p = {};

        for(var i = 0, len = cm.getColumnCount(); i < len; i++){
            p.id = cm.getColumnId(i);
            p.value = cm.getColumnHeader(i) || "";
            if(p.id=='checker' && this.grid.getSelectionModel().singleSelect===true) p.value='';
            p.style = this.getColumnStyle(i, true);
            if(cm.config[i].align == 'right'){
                p.istyle = 'padding-right:16px';
            }
            cb[cb.length] = ct.apply(p);
        }
        return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'});
	},
    onDataChange : function(){
        //debugger;
        this.refresh();
        this.updateHeaderSortState();
    }

});

Ext.override(Ext.data.Store,{
    loadRecords : function(o, options, success){
        //debugger;
        if(!o || success === false){
            if(success !== false){
                this.fireEvent("load", this, [], options);
            }
            if(options.callback){
                options.callback.call(options.scope || this, [], options, false);
            }
            return;
        }
        var r = o.records, t = o.totalRecords || r.length;
        if(!options || options.add !== true){
            if(this.pruneModifiedRecords){
                this.modified = [];
            }
            for(var i = 0, len = r.length; i < len; i++){
                r[i].join(this);
            }
            if(this.snapshot){
                this.data = this.snapshot;
                delete this.snapshot;
            }
            this.data.clear();
            this.data.addAll(r);
            this.totalLength = t;
            this.applySort();
            this.fireEvent("datachanged", this);
        }else{
            this.totalLength = Math.max(t, this.data.length+r.length);
            this.add(r);
        }
        this.fireEvent("load", this, r, options);
        if(options.callback){
            options.callback.call(options.scope || this, r, options, true);
        }
    },
    removeByIndex : function(index){
        //var index = this.data.indexOf(record);
        this.data.removeAt(index);
        if(this.pruneModifiedRecords){
            this.modified.remove(record);
        }
        if(this.snapshot){
            this.snapshot.remove(record);
        }
        this.fireEvent("remove", this, {}, index);
    }
});
//=======================================================================================================
//重载 以识别正确的空的返回
//=======================================================================================================
Ext.override(Ext.data.HttpProxy,{
    loadResponse : function(o, success, response){
        //debugger;
        delete this.activeRequest;
        if(!success){
            this.fireEvent("loadexception", this, o, response);
            o.request.callback.call(o.request.scope, null, o.request.arg, false);
            return;
        }
        var result;
        try {
            result = o.reader.read(response);
            //if(!result.success)
            //throw {message: result.errMsg,name:'sail'};
        }catch(e){
            //debugger;
            o.request.arg.errorInfo = e.message;
            try{
                var getData = eval("("+response.responseText+")");
                o.request.arg.datasetFlag = (getData.dataset.response.success=="true")?true:false;;
                o.request.arg.errorInfo = getData.dataset.response.content;

            }catch(e){
                o.request.arg.errorInfo = "JSON转换异常 或 没有找到dataset.response.success标志！"
            }
            
            this.fireEvent("loadexception", this, o, response, e);
            o.request.callback.call(o.request.scope, null, o.request.arg, false);
            return;
        }
        this.fireEvent("load", this, o, o.request.arg);
        o.request.callback.call(o.request.scope, result, o.request.arg, true);
    }
});

//=======================================================================================================
//重载 以适应单调记录返回
//=======================================================================================================
Ext.override(Ext.data.JsonReader,{
    readRecords:function(o){
        //debugger;
        this.jsonData = o;
        var s = this.meta, Record = this.recordType,
            f = Record.prototype.fields, fi = f.items, fl = f.length;

        //debugger;
        if (!this.ef) {
            if(s.totalProperty) {
	            this.getTotal = this.getJsonAccessor(s.totalProperty);
	        }
	        if(s.successProperty) {
	            this.getSuccess = this.getJsonAccessor(s.successProperty);
	        }
	        
	        if(s.messageProperty){
	            this.getMessage = this.getJsonAccessor(s.messageProperty);
	        }
	        
	        this.getRoot = s.root ? this.getJsonAccessor(s.root) : function(p){return p;};
	        if (s.id) {
	        	var g = this.getJsonAccessor(s.id);
	        	this.getId = function(rec) {
	        		var r = g(rec);
		        	return (r === undefined || r === "") ? null : r;
	        	};
	        } else {
	        	this.getId = function(){return null;};
	        }
            this.ef = [];
            for(var i = 0; i < fl; i++){
                f = fi[i];
                var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
                this.ef[i] = this.getJsonAccessor(map);
            }
        }
        
    	var root = this.getRoot(o);
    	var c = (root.length)?root.length:1, totalRecords = c, success = true;
    	var errMsg = "后台错误...";
    	
    	if(s.totalProperty){
            var v = parseInt(this.getTotal(o), 10);
            if(!isNaN(v)){
                totalRecords = v;
            }
        }
        if(s.successProperty){
            var v = this.getSuccess(o);
            if(v === false || v === 'false'){
                success = false;
                if(s.messageProperty){
                    errMsg = this.getMessage(o);
                }
            }
        }
        var records = [];
	    for(var i = 0; i < c; i++){
		    var n = (c==1)?root:root[i];
	        var values = {};
	        var id = this.getId(n);
	        for(var j = 0; j < fl; j++){
	            f = fi[j];
                var v = this.ef[j](n);
                values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue);
	        }
	        var record = new Record(values, id);
	        record.json = n;
	        records[i] = record;
	    }
	    
	    return {
	        success : success,
	        errMsg  : errMsg,
	        records : records,
	        totalRecords : totalRecords
	    };
    }
});






//=================================================================================================
//本地化
//=================================================================================================
Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">加载中...</div>';
if(Ext.View){Ext.View.prototype.emptyText = "";}
if(Ext.grid.Grid){Ext.grid.Grid.prototype.ddText = "{0} 选择行";}
if(Ext.TabPanelItem){Ext.TabPanelItem.prototype.closeText = "关闭";}
if(Ext.form.Field){Ext.form.Field.prototype.invalidText = "输入值非法";}
Date.monthNames = ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"];
Date.dayNames = ["日","一","二","三","四","五","六"];
if(Ext.MessageBox){
   Ext.MessageBox.buttonText = {
      ok     : "确定",
      cancel : "取消",
      yes    : "是",
      no     : "否"
   };
}
if(Ext.util.Format){
   Ext.util.Format.date = function(v, format){
      if(!v) return "";
      if(!(v instanceof Date)) v = new Date(Date.parse(v));
      return v.dateFormat(format || "y年m月d日");
   };
}
if(Ext.DatePicker){
   Ext.apply(Ext.DatePicker.prototype, {
      todayText         : "今天",
      minText           : "日期在最小日期之前",
      maxText           : "日期在最大日期之后",
      disabledDaysText  : "",
      disabledDatesText : "",
      monthNames        : Date.monthNames,
      dayNames          : Date.dayNames,
      nextText          : '下月 (Control+Right)',
      prevText          : '上月 (Control+Left)',
      monthYearText     : '选择一个月 (Control+Up/Down 来改变年)',
      todayTip          : "{0} (空格键选择)",
      format            : "y年m月d日",
      okText            : "确定",
      cancelText        : "取消"
   });
}
if(Ext.PagingToolbar){
   Ext.apply(Ext.PagingToolbar.prototype, {
      beforePageText : "第",
      afterPageText  : "页共 {0} 页",
      firstText      : "第一页",
      prevText       : "前一页",
      nextText       : "下一页",
      lastText       : "最后页",
      refreshText    : "刷新",
      displayMsg     : "显示 {0} - {1}，共 {2} 条",
      emptyMsg       : '没有数据需要显示'
   });
}
if(Ext.form.TextField){
   Ext.apply(Ext.form.TextField.prototype, {
      minLengthText : "该输入项的最小长度是 {0}",
      maxLengthText : "该输入项的最大长度是 {0}",
      blankText     : "该输入项为必输项",
      regexText     : "",
      emptyText     : null
   });
}
if(Ext.form.NumberField){
   Ext.apply(Ext.form.NumberField.prototype, {
      minText : "该输入项的最小值是 {0}",
      maxText : "该输入项的最大值是 {0}",
      nanText : "{0} 不是有效数值"
   });
}
if(Ext.form.DateField){
   Ext.apply(Ext.form.DateField.prototype, {
      disabledDaysText  : "禁用",
      disabledDatesText : "禁用",
      minText           : "该输入项的日期必须在 {0} 之后",
      maxText           : "该输入项的日期必须在 {0} 之前",
      invalidText       : "{0} 是无效的日期 - 必须符合格式： {1}",
      format            : "y年m月d日"
   });
}
if(Ext.form.ComboBox){
   Ext.apply(Ext.form.ComboBox.prototype, {
      loadingText       : "加载...",
      valueNotFoundText : undefined
   });
}
if(Ext.form.VTypes){
   Ext.apply(Ext.form.VTypes, {
      emailText    : '该输入项必须是电子邮件地址，格式如： "user@domain.com"',
      urlText      : '该输入项必须是URL地址，格式如： "http:/'+'/www.domain.com"',
      alphaText    : '该输入项只能包含字符和_',
      alphanumText : '该输入项只能包含字符,数字和_'
   });
}
if(Ext.grid.GridView){
   Ext.apply(Ext.grid.GridView.prototype, {
      sortAscText  : "正序",
      sortDescText : "逆序",
      lockText     : "锁列",
      unlockText   : "解锁列",
      columnsText  : "列"
   });
}
if(Ext.grid.PropertyColumnModel){
   Ext.apply(Ext.grid.PropertyColumnModel.prototype, {
      nameText   : "名称",
      valueText  : "值",
      dateFormat : "y年m月d日"
   });
}
if(Ext.layout.BorderLayout.SplitRegion){
   Ext.apply(Ext.layout.BorderLayout.SplitRegion.prototype, {
      splitTip            : "拖动来改变尺寸.",
      collapsibleSplitTip : "拖动来改变尺寸. 双击隐藏."
   });
}

//=================================================================================================
//处理blank image
//=================================================================================================
function getBlankImgPath(allPath){
    
    var infos = allPath.split("/");
    var imgPath = "support/resources/images/default/s.gif";
    
    var begin = (infos[0]=="")?1:0;
    var blankImgPath = "/";
    
    for(var i=begin;i<infos.length;i++){
        if(infos[i]=='WebContent') {
            blankImgPath+=infos[i]+'/';
            break;
        }
        else if(infos[i]=='business'){
            //blankImgPath+='WebContent/';
            break;
        }else{
            blankImgPath+=infos[i]+'/';
        }
    }
    
    //debugger;
    blankImgPath +=imgPath;
    Ext.BLANK_IMAGE_URL =  blankImgPath;   
}
getBlankImgPath(window.location.pathname);
//Ext.BLANK_IMAGE_URL = '/' + window.location.pathname.split('/', 2)[1] + '/support/resources/images/default/s.gif';
//Ext.BLANK_IMAGE_URL= '../../ext2/resources/images/default/s.gif';

﻿//=======================================================================================
//类名 ： Sail.Template
//说明 ： HTML 模板
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================
Sail.namespace('Sail.util');

Sail.util.Format = function(){
    var trimRe = /^\s+|\s+$/g;
    return {

        ellipsis : function(value, len){
            if(value && value.length > len){
                return value.substr(0, len-3)+"...";
            }
            return value;
        },


        undef : function(value){
            return value !== undefined ? value : "";
        },


        defaultValue : function(value, defaultValue){
            return value !== undefined && value !== '' ? value : defaultValue;
        },


        htmlEncode : function(value){
            return !value ? value : String(value).replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");
        },


        htmlDecode : function(value){
            return !value ? value : String(value).replace(/&amp;/g, "&").replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/&quot;/g, '"');
        },


        trim : function(value){
            return String(value).replace(trimRe, "");
        },


        substr : function(value, start, length){
            return String(value).substr(start, length);
        },


        lowercase : function(value){
            return String(value).toLowerCase();
        },


        uppercase : function(value){
            return String(value).toUpperCase();
        },


        capitalize : function(value){
            return !value ? value : value.charAt(0).toUpperCase() + value.substr(1).toLowerCase();
        },

        // private
        call : function(value, fn){
            if(arguments.length > 2){
                var args = Array.prototype.slice.call(arguments, 2);
                args.unshift(value);
                return eval(fn).apply(window, args);
            }else{
                return eval(fn).call(window, value);
            }
        },


        usMoney : function(v){
            v = (Math.round((v-0)*100))/100;
            v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
            v = String(v);
            var ps = v.split('.');
            var whole = ps[0];
            var sub = ps[1] ? '.'+ ps[1] : '.00';
            var r = /(\d+)(\d{3})/;
            while (r.test(whole)) {
                whole = whole.replace(r, '$1' + ',' + '$2');
            }
            v = whole + sub;
            if(v.charAt(0) == '-'){
                return '-$' + v.substr(1);
            }
            return "$" +  v;
        },


        date : function(v, format){
            if(!v){
                return "";
            }
            if(!(v instanceof Date)){
                v = new Date(Date.parse(v));
            }
            return v.dateFormat(format || "m/d/Y");
        },


        dateRenderer : function(format){
            return function(v){
                return Ext.util.Format.date(v, format);
            };
        },

        // private
        stripTagsRE : /<\/?[^>]+>/gi,
        

        stripTags : function(v){
            return !v ? v : String(v).replace(this.stripTagsRE, "");
        },

        stripScriptsRe : /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,


        stripScripts : function(v){
            return !v ? v : String(v).replace(this.stripScriptsRe, "");
        },


        fileSize : function(size){
            if(size < 1024) {
                return size + " bytes";
            } else if(size < 1048576) {
                return (Math.round(((size*10) / 1024))/10) + " KB";
            } else {
                return (Math.round(((size*10) / 1048576))/10) + " MB";
            }
        },

        math : function(){
            var fns = {};
            return function(v, a){
                if(!fns[a]){
                    fns[a] = new Function('v', 'return v ' + a + ';');
                }
                return fns[a](v);
            }
        }()
    };
}();
Sail.Template = function(html){
    var a = arguments;
    if(html instanceof Array){
        html = html.join("");
    }else if(a.length > 1){
        var buf = [];
        for(var i = 0, len = a.length; i < len; i++){
            if(typeof a[i] == 'object'){
                Sail.apply(this, a[i]);
            }else{
                buf[buf.length] = a[i];
            }
        }
        html = buf.join('');
    }
    
    this.html = html;
    if(this.compiled){
        this.compile();   
    }
};
Sail.Template.prototype = {
    re : /\{([\w-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g,
    
    applyTemplate : function(values){
        if(this.compiled){
            return this.compiled(values);
        }
        var useF = this.disableFormats !== true;
        var fm = Sail.util.Format, tpl = this;
        var fn = function(m, name, format, args){
            if(format && useF){
                if(format.substr(0, 5) == "this."){
                    return tpl.call(format.substr(5), values[name], values);
                }else{
                    if(args){
                        // quoted values are required for strings in compiled templates, 
                        // but for non compiled we need to strip them
                        // quoted reversed for jsmin
                        var re = /^\s*['"](.*)["']\s*$/;
                        args = args.split(',');
                        for(var i = 0, len = args.length; i < len; i++){
                            args[i] = args[i].replace(re, "$1");
                        }
                        args = [values[name]].concat(args);
                    }else{
                        args = [values[name]];
                    }
                    return fm[format].apply(fm, args);
                }
            }else{
                return values[name] !== undefined ? values[name] : "";
            }
        };
        return this.html.replace(this.re, fn);
    }
}
Sail.Template.prototype.apply = Sail.Template.prototype.applyTemplate;




//=======================================================================================
//类名 ： debugMsg
//说明 ： 
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================
Sail.debugMsg = function(config){
    Sail.apply(this,config);
};
Sail.debugMsg.prototype = {
    msg : [],
    history : [],
    
    push : function(){
        var a = arguments;
        if(a.length==1){
            if(a[0]==""){
                this.msg.push("");
            }else{
                this.msg.push("● "+a[0]);
            }
        }else if(a.length==2){
            //debugger;
            var level = a[0].level||0;
            var space = [];
            for(var i=0;i<(level-1)*4;i++) space.push("&nbsp;");
            
            this.msg.push(space.join('')+"● <font color=blue>["+a[0].name+"]</font> "+a[1]);

        }
    },
    clear : function(){
        this.msg = [];
    },
    save : function(title){
        this.history.push({name:title||"",msg:[].concat(this.msg)});
        this.msg.clear();
    },
    
    show : function(){
        var html = [];
        
        html.push("<br><br><br><div style='padding:4 4 4 4;overflow:auto;border:1px #15426B solid;width:100%;height:520'>");
        html.push(this.msg.join("<br>"));
        html.push("</div>");

        Sail.showMsg(html.join(''));
    }
}
var sdm = new Sail.debugMsg();




//=======================================================================================
//类名 ： stringBuffer
//说明 ： 
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================
Sail.stringBuffer = function(){
    this.length = 0;
    this.infoArray = [];
    
    this.toString= function () {                //转换成字符串
        var splitChar = (arguments.length==1)?arguments[0]:"";
        return this.infoArray.join(splitChar);
    };
    
    this.getLen = function(){
        return this.infoArray.length;
    };
    
    this.push=function(str){
        if(str instanceof Array){
            this.infoArray = this.infoArray.concat(str);
            this.length+=str.length;
        }
        else{
            this.infoArray.push(str);
            this.length++;
        }
    }
    
    this.pop = function(){
        return this.infoArray.pop();
    }
    
    this.slice = function(){
        
        var start = arguments[0];
        var end   = arguments[1];
        
        if(start!=undefined && end!=undefined)
            return this.infoArray.slice(start,end);
        else{
            if(start!=undefined)
                return this.infoArray.slice(start);
            else
                return;
        }
    }
    
    this.clean= function () {
        this.length=0;
        this.infoArray = [];
    }
    
    this.distinct = function(){
        return this.infoArray.distinct();
    }
    
    this.repeated = function(){
        return this.infoArray.repeated();
    }
    
    this.replace = function(findstr,replacestr){
        var count = 0;
        for(var i=0;i<this.length;i++){
            
            if(this.infoArray[i]==findstr){
                this.infoArray[i] = replacestr;
                count++;
            }
        }
        return count;
    }
    
    this.remove = function(o){
        this.infoArray  = this.infoArray.removeAll(o);
        var removeCount = this.length-this.infoArray.length;
        this.length = this.infoArray.length;
        return removeCount;
    }
}




//=======================================================================================
//类名 ： 
//说明 ： 一组临时的关于日期的公共函数
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================
function GetFirstWeek(year,month){
  return (new Date(year,month-1,1)).getDay()
}
function GetThisDays(year,month){
  return (new Date(year,month,0)).getDate()
}
function GetLastDays(year,month){
  return (new Date(year,month-1,0)).getDate()
}
function FullNumber(num){
  return (parseInt(num,10)<10)?"0"+num:""+num;
}
function GetAppointedMonthCalendar(year,month,day){

  var _year=(year==null)?2008:parseInt(year,10);
  var _month=(month==null)?1:parseInt(month,10);
  var _day=(day==null)?1:parseInt(day,10);
  
  var _lastMonth = _month-1;
  var _lastYear  = _year-1;
  var _nextMonth = _month+1;
  var _nextyear  = _year+1;
  
  var fw=GetFirstWeek(_year,_month);
  var ld=GetLastDays(_year,_month);
  var td=GetThisDays(_year,_month);

  var isnd=false;
  var d=1;

  var aWeek=[];
  var aWeekFlag=[];
  var allDay = [];
  var allDayFlag = [];
  var tf = (fw==0)?fw+7:fw;     //如第一天是星期天.+7.保证可以看到上个月的日期

  //----------------------------------------------------------------
  //第一行上月日期+第一行本月日期
  //----------------------------------------------------------------
  for (l=(ld-tf+1);l<=ld;l++)  {
    var tmpDate = (_lastMonth==0)?""+_lastYear+"-12-"+FullNumber(l):_year+"-"+FullNumber(_lastMonth)+"-"+FullNumber(l);
    aWeek.push(tmpDate);
    aWeekFlag.push(0);
  }
  
  for (f=tf;f<=6;f++) {
    aWeek.push(_year+"-"+FullNumber(_month)+"-"+FullNumber(d));
    aWeekFlag.push(1);
    d++;
  }
  allDay.push(aWeek);
  allDayFlag.push(aWeekFlag);

  //----------------------------------------------------------------
  //其他行本月日期
  //----------------------------------------------------------------
  for (i=2;i<7;i++){
    aWeek = [];
    aWeekFlag = [];
    
    for (j=1;j<8;j++){
      if (isnd){                            //下个月的日期
        var tmpDate = (_nextMonth==13)?""+_nextyear+"-01-"+FullNumber(d):_year+"-"+FullNumber(_nextMonth)+"-"+FullNumber(d);
        aWeek.push(tmpDate);
        aWeekFlag.push(0);
      }else{                                //本月的日期
        aWeek.push(_year+"-"+FullNumber(_month)+"-"+FullNumber(d));
        aWeekFlag.push(1);
      }
      
      if (d==td){       //判断是否为本月的日期
        isnd=true;
        d=0;
      }
      d++;
    }
    allDay.push(aWeek);
    allDayFlag.push(aWeekFlag);
  }
  //debugger;
  alert(allDay.join("\n")+"\n\n"+allDayFlag.join("\n"));
  return {dateList:allDay,dataFlag:allDayFlag};
}
function IsPinYear(year){
    return (0==year%4&&((year%100!=0)||(year%400==0)))?true:false;
}
function formatDayStrIncludeYear(dayStr){
  
  var tmpDayStr=dayStr.split("-");
  var month = parseInt(tmpDayStr[1],10);
  var day   = parseInt(tmpDayStr[2],10);
  return tmpDayStr[0]+"-"+((month>9)?month:"0"+month)+"-"+((day>9)?day:"0"+day);
}
function sys_getdatelistbetween(mybegin,myend){
  var tmpbegin= (mybegin.indexOf('-')==-1)?mybegin:mybegin.replaceAll("-","");

  var tmpend= (myend.indexOf('-')==-1)?myend:myend.replaceAll("-","");
  //var tmpend  = myend;
  var monthincludedays= "31,28,31,30,31,30,31,31,30,31,30,31";
  var monthincludedaysarray=monthincludedays.split(",");
  var returnstr="";
  
  //-------------------------------------------------------------------
  //-------------------------------------------------------------------
  if(tmpend<tmpbegin){
    var tmpvalue=tmpend;
    tmpend=tmpbegin;
    tmpbegin=tmpvalue;
  }

  //-------------------------------------------------------------------
  //-------------------------------------------------------------------
  var tmpbegin_year=eval(tmpbegin.substring(0,4)+"+0");     //取开始日期 年
  var tmpend_year=eval(tmpend.substring(0,4)+"+0");         //取结束日期 年
  var tmpbegin_month=eval(tmpbegin.substring(4,6)+"+0");    //取开始日期 月
  var tmpend_month=eval(tmpend.substring(4,6)+"+0");        //取结束日期 月
  var tmpbegin_day=eval(tmpbegin.substring(6,8)+"+0");      //取开始日期 日
  var tmpend_day=eval(tmpend.substring(6,8)+"+0");          //取结束日期 日
  
  //-------------------------------------------------------------------
  //计算时间间隔中的月度，并取得字串
  //-------------------------------------------------------------------
  for(var i=tmpbegin_year;i<=tmpend_year;i++){
    if(tmpbegin_year!=tmpend_year){
      if(i==tmpbegin_year){
        for(var k=1;k<13;k++){
          if(k>tmpbegin_month)
            returnstr+=tmpbegin_year+"-"+k+",";
        }
      }
      else if(i==tmpend_year){
        for(var k=1;k<13;k++){
          if(k<tmpend_month)
            returnstr+=tmpend_year+"-"+k+",";
        }
      }
      else{
        for(var k=1;k<13;k++){
          returnstr+=i+"-"+k+",";
        }
      }
    }else{
      for(var k=tmpbegin_month+1;k<tmpend_month;k++){
        returnstr+=tmpbegin_year+"-"+k+",";
      }
    }
  }
  
  //-------------------------------------------------------------------
  //计算开始月所选日期后续日期
  //-------------------------------------------------------------------
  var daylist=[];
  if(tmpbegin_month==tmpend_month && tmpbegin_year==tmpend_year){
    for(var i=tmpbegin_day;i<=tmpend_day;i++){
      daylist.push(formatDayStrIncludeYear(tmpend_year+"-"+tmpend_month+"-"+i));
    }
  }else{
    if(IsPinYear(tmpbegin_year))
      monthincludedaysarray[1]="29";
    else
      monthincludedaysarray[1]="28";
    for(var i=tmpbegin_day;i<=monthincludedaysarray[tmpbegin_month-1];i++){
      daylist.push(formatDayStrIncludeYear(tmpbegin_year+"-"+tmpbegin_month+"-"+i));
    }
    for(var i=1;i<=tmpend_day;i++){
      daylist.push(formatDayStrIncludeYear(tmpend_year+"-"+tmpend_month+"-"+i));
    }
  }
  
  //-------------------------------------------------------------------
  //将时间间隔月度串转换为日期串
  //-------------------------------------------------------------------
  if(returnstr.length>0){
    for(var i=0;i<returnstr.split(",").length-1;i++){
      
      if(IsPinYear(returnstr.split(",")[i].split("-")[0]))
        monthincludedaysarray[1]="29";
      else
        monthincludedaysarray[1]="28";
      
      for(var k=1;k<=monthincludedaysarray[eval(returnstr.split(",")[i].split("-")[1]+"-1")];k++)
        daylist.push(formatDayStrIncludeYear(returnstr.split(",")[i]+"-"+k));
    }
  }
  
  //returnstr=daylist;
  return daylist;
}
﻿//=======================================================================================
//类名 ： Sail.layoutConstructor
//说明 ： 区域布局构造器
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================
Sail.layoutConstructor = function(config){

    //-----------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------
    this.padding= {left:5,right:5,top:5,bottom:5};
    this.space  = {row:10,col:10};

    //-----------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------
    this.constructTo  = null;
    this.layoutConfig = {};
    this.layout = {};
    this.items  = [];    
    
    this.width;
    this.height;
    this.executor;
    
    //-----------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------
    Sail.apply(this, config);       //覆盖配置项
    
    var rObj = this.initialize()    //初始化数据结构
    //if(rObj.success===true){
    //    this.doLayout();
    //}else{
    //    alert(rObj.msg);
    //}
}

Sail.layoutConstructor.prototype = {
    //===================================================================================
    //方法 ： initialize data struct
    //参数 ： void
    //返回 :  obj
    //说明 ： 
    //===================================================================================
    initialize : function(){

        //if(this.constructTo==undefined){
        //    return {success:false,msg:"没有找到目标容器对象！"};
        //}
        
        if(this.layoutConfig==undefined)        this.repairLayoutConfig();
        if(this.layout==undefined){              
            this.repairLayout();
        }
        else {
            this.formatLayout();
        }
            
        //if(typeof this.constructTo =="string")  this.repairConstructTo();
        //待补更严格的判定...
        
        //if(this.width==undefined||this.height==undefined){
        //    return {success:false,msg:"没有布局区域的尺寸数据！"};
        //}
        if(this.isSimulation!==true){
            this.width =(this.width==undefined) ?this.constructTo.getWidth():this.width;
            this.height=(this.height==undefined)?this.constructTo.getHeight():this.height;
        }

        return {success:true};
    },

    //===================================================================================
    //方法 ： repair somethings
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    repairLayoutConfig : function(){
        this.layoutConfig = {columns : 1};        
    },

    repairLayout : function(){
        this.layout = [];
        var _executor = this.executor;
        if(this.constructTo!=undefined && this.executor==undefined){
            _executor = (this.constructTo.title==undefined)?this.constructTo.name:this.constructTo.title;
        }
        
        this.items = (this.items instanceof Array)?this.items:[this.items];
        for(var i=0;i<this.items.length;i++){
            if(this.items[i]==undefined){
                //debugger;
                var str = "【layout】：<"+_executor+"> 定义缺失，请检查items定义数组中是否多了 逗号！\n";
                
                alert(str);
            }else{
                this.layout.push({
                    items :[ { name:this.items[i].name}]
                });
            }
        }
    },

    formatLayout : function(){
        if(!Sail.isObjArray(this.layout)){
            var ray = [];
            for(var i=0;i<this.layout.length;i++){
                var o = {items:[]};
                for(var j=0;j<this.layout[i].length;j++){
                    if(typeof this.layout[i][j]=='object'){
                        var oo = {};
                        Sail.apply(oo,this.layout[i][j]);
                        o.items.push(oo);
                    }else{
                        o.items.push({name:this.layout[i][j]});
                    }
                }
                ray.push(o);
            }
            this.layout = ray;
        }
    },
    
    repairConstructTo : function(){
        this.constructTo = document.getElementById(this.constructTo);
    },
    
    //===================================================================================
    //方法 ： repairColModel
    //参数 ： void
    //返回 :  void
    //说明 ： 修补关于布局模式的行列描述数据模型
    //        行合并补齐到合并的最后一行的定义中
    //        行、列合并描述单元以空对象补齐
    //        {name:""}
    //===================================================================================
    repairColModel : function(){
        var len = this.layout.length;
        
        //-------------------------------------------------------------------------------
        //补齐colspan导致的数组缺失
        //-------------------------------------------------------------------------------
        for(var i=0;i<len;i++){
            //20090723 by yjj 屏蔽引用，引用导致items动态计算错误
            //因为循环中插入数据，导致items发生变化
            //var _items = this.layout[i]["items"];             
            for(var j=0;j<this.layout[i]["items"].length;j++){
                if(this.layout[i]["items"][j].colspan!=undefined){
                    var _insert = [];
                    for(var k=0;k<this.layout[i]["items"][j].colspan-1;k++)  _insert.push({name:''});
                    this.layout[i].items = this.layout[i]["items"].insertItems(j,_insert);
                }
            }
        }
        
        //-------------------------------------------------------------------------------
        //补齐rowspan导致的数组缺失
        //-------------------------------------------------------------------------------
        var exchangeMark = [];
        for(var i=0;i<len;i++){                             //遍历行定义对象
            var _items = this.layout[i].items;              //
            for(var j=0;j<_items.length;j++){               //编列列定义对象
                if(_items[j].rowspan!=undefined){           //该列出现行合并定义
                    var cols = (_items[j].colspan==undefined)?1:_items[j].colspan;
                    var newItems = [];
                    for(var m=0;m<cols;m++) newItems.push({name:''});
                    
                    for(var k=0;k<_items[j].rowspan-1;k++){ //补齐空定义
                        this.layout[i+1+k].items = this.layout[i+1+k].items.insertItems(j-1,newItems);
                    }
                    exchangeMark.push({source:[i,j],target:[i+_items[j].rowspan-1,j]});
                }
            }
        }
        
        //-------------------------------------------------------------------------------
        //交换行合并定义到末行位置
        //-------------------------------------------------------------------------------
        for(var i=0;i<exchangeMark.length;i++){
            var rowS = exchangeMark[i].source[0];
            var colS = exchangeMark[i].source[1];
            var rowT = exchangeMark[i].target[0];
            var colT = exchangeMark[i].target[1];
            
            var tmp = this.layout[rowS].items[colS];
            this.layout[rowT].items[colT]=tmp;
            this.layout[rowS].items[colS] = {name:''};
        }
        
        
        //-------------------------------------------------------------------------------
        //如果行列定义有错误，显示错误信息
        //-------------------------------------------------------------------------------
        var columns = this.layoutConfig.columns;        
        var colInfo = [];
        var _executor = this.executor;
        if(this.constructTo!=undefined && this.executor==undefined){
            _executor = (this.constructTo.title==undefined)?this.constructTo.name:this.constructTo.title;
        }
        for(var i=0;i<len;i++){
            var colCount = this.layout[i]['items'].length
            if(colCount!=columns){
                colInfo.push("【layout】：<"+_executor+"> 第 "+(i+1)+" 行定义错误！预定义 "+columns+" 列，实际检测到 "+colCount+" 列。\n");
            }
        }
        if(colInfo.length>0){
            //alert(colInfo.join(""));
        }
    },
    

    //===================================================================================
    //方法 ： get somethings
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    getWidth : function(){
        return this.width;
    },
    getHeight : function(){
        return this.height;
    },
    getItemByDefine : function(name){
        for(var i=0;i<this.items.length;i++){
            if(this.items[i].name==undefined)
                this.items[i].name = this.items[i].title;
                
            var sValue = (this.items[i].name==undefined)?this.items[i].title:this.items[i].name;
            if(sValue==name) return this.items[i];
        }
        return null;
    },

    formatCellWidth : function(scale,aw,colNum){
        var scaleValue=aw/colNum;
        if(typeof scale =='string'){
            scale = scale.replace("%",'');
            scaleValue = parseInt(scale,10)/100;
        }else if(typeof scale =='number'){
            scaleValue = (scale<1)?scale:scale/100;
        }else{
        }
        return aw*scaleValue;
    },
    
    needCreate : function(wConfig){

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(wConfig.type=='form')    return true;
        
        if(wConfig.type=='tabs'){
            if(wConfig.autoHeight===true) return true;
        }
        //....补充规则，，太阳，，有没有一种方法不用在这里写代码，，，
                
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        return false;
    },
    
    getCellWidth : function(col){
    },
    
    getWidthByCol : function(widths,begin,col){
        var rv =0;
        for(var i=begin;i<col;i++)    
            rv+=widths[i];
        return rv;
    },
    
    //===================================================================================
    //方法 ： doLayout
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    computeHeight : function(){
        var rowCount = this.layout.length;          //行数
        var colCount = this.layoutConfig.columns;   //列数
        
        var rowHeight = [];
        this.repairColModel();                      //修补关于布局模式的行列描述数据模型                
        for(var i=0;i<rowCount;i++){                //逐行
            var _heights = [];
            var _itemsD  = this.layout[i]["items"]; //得到当前行子元素定义数组

            for(var j=0;j<colCount;j++){
                var od = _itemsD[j];                //取得布局定义中当前子元素的定义(name)
                if(od==undefined) continue;
                if(od.name=="") continue;           //空对象，继续

                var wc = this.getItemByDefine(od.name);
                if(wc==null && wc==undefined){      //定义缺失，警告，继续
                    //debugger;
                    alert("组件："+od.name+"，没有找到定义！");
                    continue;
                }
                wc.widgetPrefix= this.widgetPrefix;

                var w = eval("new "+this.widgetPrefix+""+wc.type+"(wc);");
                //Sail.apply(w,wc);
                if(wc.height==undefined) wc.autoHeight = true;
                
                wc.height= (wc.height==undefined)?w.getIntendingHeight():wc.height;

                if(od.rowspan!=undefined && wc.autoHeight!==true){
                    var rh = this.getWidthByCol(rowHeight,i - od.rowspan+1,i)+(od.rowspan-1)*this.space.row;
                    _heights.push(wc.height-rh);
                }else{
                    _heights.push(wc.height);           //记录定义高度
                }
            }
            var maxHeight = _heights.max();             //取得各个子元素中最大高度
            rowHeight.push(maxHeight);
        }
        
        return rowHeight.sum()+this.padding.top+this.padding.bottom+this.space.row*(rowCount-1);
    },
    
    //===================================================================================
    //方法 ： doLayout
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    addOperate : function(oi){
        var name = oi.item.name;
        var type = oi.type;
        var value= oi.value;
        
        oi.item[type] = value;
        
        if(this.operateList[name]==undefined){
            this.operateList.items = this.operateList.items ||[];
            this.operateList.items.push(name);
            
            this.operateList[name]={type:{}};
            this.operateList[name].type[type]=value;
        }else{
            this.operateList[name].type[type]=value;
        }
    },
    
    doLayout : function(level){

        if(this.alreadyCreate!==true){
            sdm.push("");
            sdm.push(this.constructTo," layout begin...");
        }

        this.operateList = {items:[]};

        var itemLevel = level+1;
        
        var haveScroll = false;                     //是否出现滚动
        var c2 = this.constructTo;                  //构造的目标容器对象

        var rowCount = this.layout.length;          //行数
        var colCount = this.layoutConfig.columns;   //列数
        
        //-------------------------------------------------------------------------------
        var w_table  = this.getWidth();             //目标对象宽度 及 布局组件可用宽度
        var w_actual = w_table-this.padding.left-this.padding.right-(colCount-1)*this.space.col;

        var h_height = this.getHeight();            //目标对象高度 及 布局组件可用高度
        var h_actual = this.getHeight()-this.padding.top-this.padding.bottom-this.space.row*(rowCount-1);

        var h_row    = [];                          //行高
        var w_col    = [];                          //列宽
        
        if(this.layoutConfig.width!=undefined && this.layoutConfig.width instanceof Array){
            for(var i=0;i<this.layoutConfig.width.length;i++){
                w_col[i] = this.formatCellWidth(this.layoutConfig.width[i],w_actual,colCount);
            }
        }else{
            for(var i=0;i<colCount;i++)    w_col[i]  = w_actual/colCount;
        }

        //-------------------------------------------------------------------------------
        var cConfig = {
            level       : itemLevel,              //20090902 add prototype level
            parentDiv   : (this.parentDiv==undefined)?c2.getEl():this.parentDiv,
            ownerFrame  : (this.ownerFrame==undefined)?c2.getBelongedFrame():this.ownerFrame,
            frame       : (this.ownerFrame==undefined)?c2.getBelongedFrame():this.ownerFrame,
            ownerGroup  : (this.ownerGroup==undefined)?c2.getChildren():this.ownerGroup,
            owner       : c2,
            page        : (this.page==undefined)?c2.getBelongedPage():this.page,
            widgetPrefix: c2.widgetPrefix
        };
        var _frame = (this.ownerFrame==undefined)?c2.getBelongedFrame():this.ownerFrame
        
        //-------------------------------------------------------------------------------
        if(this.alreadyCreate!==true){
            this.repairColModel();                  //修补关于布局模式的行列描述数据模型
        }
        
        //-------------------------------------------------------------------------------
        //遍历，逐行创建并布局
        //-------------------------------------------------------------------------------
        var _tops = [];                             //声明空间，记录各行起始位置
        var _top = this.padding.top;                //当前行起始位置
        _tops.push(_top);                           //记录

        for(var i=0;i<rowCount;i++){                //逐行
            var _heights = [];
            var _itemsD  = this.layout[i]["items"]; //得到当前行子元素定义数组

            //-----------------------------------------------------------------------
            var rowspanFlag  = false;               //标志当前行是否出现行合并
            var rowspanItems = [];                  //记录当前行中行合并的信息
            
            for(var j=0;j<colCount;j++){
                var od = _itemsD[j];                //取得布局定义中当前子元素的定义(name)
                if(od==undefined) continue;
                if(od.name=="") continue;           //空对象，继续

                var wc = this.getItemByDefine(od.name);
                
                if(wc==null && wc==undefined){      //定义缺失，警告，继续
                    alert("组件："+od.name+"，没有找到定义！");
                    continue;
                }

                //-------------------------------------------------------------------
                var _cw= (od.colspan==undefined)?w_col[j]:this.getWidthByCol(w_col,j,j+od.colspan)+this.space.col*(od.colspan-1);
                cConfig.left  = this.padding.left + this.getWidthByCol(w_col,0,j)+this.space.col*j;
                cConfig.width = (wc.width!=undefined)?wc.width:_cw;
                
                if(this.alreadyCreate===true){
                    cConfig.width = _cw;
                }

                
                cConfig.type  = wc.type;
                cConfig.top   = (od.rowspan!=undefined)?_tops[i-od.rowspan+1]:_top;    
                
                //-------------------------------------------------------------------
                Sail.apply(wc,cConfig);                //追加公共定义
                if(this.alreadyCreate!==true){
                    //if(wc.type=='form') debugger;
                    var w = eval("new "+wc.widgetPrefix+""+wc.type+"(wc);");
                    
                    if(wc.height==undefined) {
                        wc.autoHeight = true;
                        w.autoHeight = true;
                    }
                    //if(w.type=='grid') debugger;
                    
                    //-------------------------------------------------------------------
                    //20090908 调试tabComponent时这里发现一个创建的大BUG...
                    //
                    //这里，按道理是不需要再一次调用 Sail.apply(w,wc)
                    //但是不调用 form grid组件有错误（别的组件未测试）
                    //
                    //组件的继承关系中 initComponent 方法 调用次序有问题
                    //需整体调试，
                    //修改 form的创建 表格的 initComponent方法
                    //
                    //目前 tabComponent组件 暂时走水路往下调试，标记之...
                    //-------------------------------------------------------------------
                    //Sail.apply(w,wc);         //2009-09-09 21:14 暂时注释 日后修正若干组件  已修改      
                
                    //if(w.type=='form') debugger;
                    wc.height= (wc.height==undefined)?w.getIntendingHeight():wc.height;
                    w.height = wc.height;
                    var _size = w.create();                 //创建 组件
                }else{
                    //debugger;
                    var w = _frame.getItem(wc.name);
                    if(w.getActualHeight!=undefined){
                        wc.height = w.getActualHeight();
                        if(i==(rowCount-1)){
                            //debugger;
                            wc.height = w.getIntendingHeight();
                            sdm.push(w,"last row form setHeight="+wc.height);
                            this.addOperate({
                                item:w,
                                type:'height',
                                value:wc.height
                            });
                        }
                    }else{
                        if(wc.autoHeight==true) {
                            //if(wc.name=='普通列表') debugger;
                            wc.height = w.getIntendingHeight();
                            sdm.push(w,"when compute setHeight="+wc.height);
                            this.addOperate({
                                item:w,
                                type:'height',
                                value:wc.height
                            });
                            
                            //w.setHeight(wc.height);
                        }else{
                            sdm.push(w,"when compute setHeight="+wc.height);
                            this.addOperate({
                                item:w,
                                type:'height',
                                value:wc.height
                            });
                            //w.setHeight(wc.height);
                        }
                    }
                    
                    w.setLeft(cConfig.left);
                    if(w.width!=cConfig.width){
                        sdm.push(w,"when compute setWidth="+cConfig.width);
                        this.addOperate({
                            item:w,
                            type:'width',
                            value:cConfig.width
                        });
                        //w.setWidth(cConfig.width);
                    }
                    w.setTop(cConfig.top);
                }
                
                if(od.rowspan!=undefined){ //&& wc.autoHeight!==true){      //2009-05-21 14:36 for DC layout
                    var rsh = this.getWidthByCol(h_row,i - od.rowspan+1,i)+(od.rowspan-1)*this.space.row;
                    _heights.push(wc.height-rsh);
                }else{
                    _heights.push(wc.height);           //记录定义高度
                }

                //-------------------------------------------------------------------
                //如果是行合并，则记录相关信息
                //-------------------------------------------------------------------
                if(od.rowspan!=undefined && wc.autoHeight===true){
                    rowspanFlag = true;                     //标志出现行合并
                    rowspanItems.push({
                        row : i,    rowspan : od.rowspan,   item : w
                    });
                }
            }
            
            //-----------------------------------------------------------------------
            //【2】创建完毕后的设置
            //-----------------------------------------------------------------------
            var maxHeight = _heights.max();                 //取得各个子元素中最大高度
            h_row.push(maxHeight);                          //记录到行高数组      
            
            _top+=maxHeight+this.space.row;                 //计算下一行起始位置
            _tops.push(_top);                               //记录每行起始位置
            
            if(i==(rowCount-1)){
                var _bottom = _top - this.space.row;
                maxHeight = (_bottom <h_height)?maxHeight +(h_height-_bottom-this.padding.bottom):maxHeight;
                h_row[h_row.length-1] = maxHeight;
            }

            //-----------------------------------------------------------------------
            //【3】当该行子元素出现行合并时的行高的处理过程
            //-----------------------------------------------------------------------
            if(rowspanFlag){
                //debugger;
                for(var k=0;k<rowspanItems.length;k++){
                    var rsi = rowspanItems[k];

                    var begin = rsi.row - rsi.rowspan+1;
                    var end   = rsi.row+1;
                    var rsiHeight = this.getWidthByCol(h_row,begin,end);
                    rsiHeight += (rsi.rowspan-1)*this.space.row;
                    
                    sdm.push(rsi.item,"when rowspan setHeight="+rsiHeight);
                    this.addOperate({
                        item:rsi.item,
                        type:'height',
                        value:rsiHeight
                    });
                    //rsi.item.setHeight(rsiHeight);
                }
            }
    
            //-----------------------------------------------------------------------
            //【4】创建完毕后的高度调整
            //-----------------------------------------------------------------------
            for(var j=0;j<colCount;j++){
                var od = _itemsD[j];                //取得布局定义中当前子元素的定义(name)
                if(od==undefined) continue;
                if(od.name=="") continue;           //空对象，继续
                //debugger;
                var widget = _frame.getItem(od.name);
                if(widget.getHeight()<maxHeight) {
                    sdm.push(widget,"when row adjust setHeight="+maxHeight);
                    this.addOperate({
                        item:widget,
                        type:'height',
                        value:maxHeight
                    });
                    //widget.setHeight(maxHeight);
                }
            }
        }
        
        this.tops = [].concat(_tops);
        this.lastBottom = _tops.pop()-this.space.row+this.padding.bottom;
        //---------------------------------------------------------------------------
        //【over】创建完毕后的宽度调整
        //---------------------------------------------------------------------------
        //if(c2.type!='tabs'){
            var h_total = h_row.sum()-this.padding.bottom;
            if(h_total>h_actual){
                for(var i=0;i<rowCount;i++){                //逐行
                    var _itemsD  = this.layout[i]["items"]; //得到当前行子元素定义数组
                    for(var j=0;j<colCount;j++){
                        var od = _itemsD[j];                //取得布局定义中当前子元素的定义(name)
                        if(od.name=="") continue;           //空对象，继续
                        
                        var w = _frame.getItem(od.name);
                        sdm.push(w,"when scroll setWidth="+(w.getWidth()-20));
                        this.addOperate({
                            item:w,
                            type:'width',
                            value:w.getWidth()-20
                        });
                        //w.setWidth(w.getWidth()-20);
                    }
                }
            }
        //}
        //debugger;
        for(var i=0;i<this.operateList.items.length;i++){
            var itemName = this.operateList.items[i];
            var item = $(itemName);
            
            var otype = this.operateList[itemName].type;
            
            if(otype.width!=undefined && otype.height!=undefined){
                item.setSize(otype.width,otype.height);
            }else{
                if(otype.width!=undefined){
                    item.setWidth(otype.width);
                }
    
                if(otype.height!=undefined){
                    item.setHeight(otype.height);
                }
            }
        }
        this.operateList = {items:[]};

        
        //---------------------------------------------------------------------------
        //---------------------------------------------------------------------------
        if(this.alreadyCreate!==true){
            sdm.push(this.constructTo," layout end...");
            sdm.push("");
        }
        
    },
    
    reLayout : function(config){
        config = config||{};
        Sail.apply(this,config);
        this.alreadyCreate = true;

        sdm.push(this.constructTo,"relayout begin...");
        this.doLayout(this.constructTo.level);
        sdm.push(this.constructTo,"relayout end...");

    }
};
﻿//=======================================================================================
//类名 ： Sail.loginInfo
//说明 ： 登录信息管理对象
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================

Sail.loginInfo = function(config){

    //-----------------------------------------------------------------------------------
    //默认信息项
    //-----------------------------------------------------------------------------------
    this.navi        = "";          //导航条
    this.opername    = "";          //登录人姓名
    this.opertype    = "";          //登录人类别
    this.operorgid   = "";          //登录人部门ID
    this.operorgname = "";          //登录人部门名称
    this.factoryName = "";          //登录人工厂名称
    this.factoryID   = "";          //登录人工厂ID
    this.opercode    = "";          //登录人编码
    this.operator    = "";          //登录人ID
    this.operfun     = "";

    //-----------------------------------------------------------------------------------
    //数据源链接URL
    //-----------------------------------------------------------------------------------
    this.url    = ""; 
    this.method = "POST";
    
    this.dataRoot    = "dataset.others";
    this.successFlag = "dataset.response.success";
    
    //-----------------------------------------------------------------------------------
    //应用参数 
    //-----------------------------------------------------------------------------------
    Sail.apply(this,config);
    
    //-----------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------
    //if(this.url!=null && this.url!=""){
    //    this.getLoginInfo();
    //}
};

Sail.loginInfo.prototype = {
    
    //===================================================================================
    //方法 ： getLoginInfo
    //参数 ： void
    //返回 :  void
    //说明 ： 获取登录信息
    //===================================================================================
    getLoginInfo : function(){
        var o = this;
        
        var _scope = (o.scope==undefined)?o:o.scope;
        
        Sail.request({
            url: o.url,
            method : o.method,
            scope: _scope,
            success: function(action,options){
                    
                var _data = eval("("+action.responseText+")"); 
                var flag = o.getSuccessFlag(_data);
                
                if(flag=="true"){
                    o.saveLoginData(_data);
                    options.scope.onLoadLoginInfoSuccess(_data,action,options,o);
                }else{
                    options.scope.onLoadLoginInfofailure(_data,action,options,o);
                }
            },

            failure: function(action,options){
                var _data = {"dataset":{"response":{"content":"获取失败！404错误！","success":"false"}}};
                options.scope.onLoadDataFailure(_data,action,options,o);
            }
        });
    },
    
    getSuccessFlag : function(data){
        return Sail.getSubObj(data,this.successFlag);
    },
    
    onLoadLoginInfoSuccess : function(dataObj,action,options,scope){
        this.saveLoginData(dataObj);
    },
    
    onLoadLoginInfofailure : function(dataObj,action,options,scope){
        var _status = action.status; 
        alert('获取登录信息失败！失败编码：'+_status); 
    },
    
    saveLoginData : function(obj){
        var o = Sail.getSubObj(obj,this.dataRoot);
        Sail.apply(this,o);
    }
};

﻿//=======================================================================================
//类名 ： Sail.frame
//说明 ： 页面结构对象
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================

Sail.frame = function(config){
    
    this.level = 1;
    
    //===========================================================================================
    //标志位
    //===========================================================================================
    this.alreadyCreate = false;         //是否已经创建该页面，默认为false（未创建）
    this.hidden        = false;         //是否是隐藏状态，默认为false（隐藏）
    
    this.widgetPrefix  = "Sail.widget.ext.";
    
    //this.layout = "simple";
    this.padding= {left:5,right:20,top:2,bottom:10};
    this.space  = {row:10,col:10};
    
    this.type   = "frame";
    //===========================================================================================
    //数据
    //===========================================================================================
    this.businessData  = {};            //业务数据对象
    this.dataChanged   = false;
    
    this.widgetsDefine = [];            //页面组件定义对象
    this.widgets       = {};            //页面组件对象（创建后）

    this.autoLoad      = true;          //是否自动加载数据
    this.loadOver      = false;         //页面数据是否加载完毕
    
    this.method        = "POST";
    this.getURL        = ""; 
    this.getUrlParameter = [];
    this.postURL       = "";
    this.successFlag   = "dataset.response.success";    
    
    this.bindDataFirst = true;
    
    //===========================================================================================
    //===========================================================================================
    this.el = null;
    this.children = [];
    this.owner = null;
    
    this.saving = false;    
    
    //===========================================================================================
    //
    //===========================================================================================
    Sail.apply(this,config);
    if(this.listeners!=undefined){
        Sail.apply(this,this.listeners);
    }
}

Sail.frame.prototype = {
    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    getBaseDiv : function(){
        return this.owner.getBaseDiv();
    },
    getBaseLayout : function(){
        return (this.owner.layout==undefined)?"relative":this.owner.layout;
    },
    getWidth : function(){
        return this.el.offsetWidth;
    },
    getHeight : function(){
        return this.el.offsetHeight;
    },
    getBelongedFrame : function(){      //获得对象所属的frame
        return this;
    },
    getBelongedPage : function(){       //获得对象所属的page
        return this.owner;
    },
    getEl : function(){
        return this.el;
    },
    getChildren : function(){
        return this.children;
    },
    getPage : function(){
        return this.owner;
    },
    
    //===================================================================================
    //方法 ： some functions for set businessData
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    setBusinessData : function(root,row,dataIndex,dataValue){       //貌似废弃
        var saveObj = null;

        if(root.length){
            root[row][dataIndex] = dataValue;
        }
        else{
            root[dataIndex] = dataValue;
        }
    },
    
    setBusinessValue : function(dataIndex,value){
        var bd       = this.businessData;               //取得业务数据
        var tmpA     = dataIndex.split(".");            //
        var rField   = tmpA.pop();                      //获得列表位置
        var droot    = Sail.getSubObj(bd,tmpA);         //获得父位置
        droot[rField]= value;
    },
    
    setBusinessListValue : function(root,field,value,row,filterFn){
        this.updateBusinessData(root,field,value,row,filterFn);
    },
    
    updateBusinessData : function(root,field,value,row,filterFn){
        //debugger;
        var subObj = Sail.getSubObj(this.businessData,root);
        
        if(subObj instanceof Array){
            if(row!=undefined){
                if(subObj[row]){
                    subObj[row][field] = (value instanceof Array)?(value[row]==undefined?"":value[row]):value;
                }else{
                    Sail.showMsg("没有找到指定的行！");
                }
            }else{
                for(var i=0;i<subObj.length;i++){
                    subObj[i][field] = (value instanceof Array)?(value[i]==undefined?"":value[i]):value;
                }
            }
        }else{
            subObj[field] = value;
        }
        //debugger;
    },
    //===================================================================================
    //方法 ： some functions for save business data to services
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    saveBusiness : function(){
        if(this.postURL=="" || this.postURL==undefined){
            alert("系统信息：\n\n没有找到保存数据的URL！");
            return;
        }
        
        if(this.saving) return;
        this.saving = true;

        //-------------------------------------------------------------------------------
        //处理参数
        //-------------------------------------------------------------------------------
        var a = arguments;
        var closeMode   = "";
        var successFunc = null;
        var failureFunc = null;
        
        if(a.length==1){
            if(typeof a[0] =='string'){
                closeMode = a[0];
            }else{
                closeMode   = a[0].mode;
                successFunc = a[0].success;
                failureFunc = a[0].failure;
            }
        }

        //-------------------------------------------------------------------------------
        //检查数据完整性
        //-------------------------------------------------------------------------------
        if(!this.checkSaveData()){
            this.saving = false;
            return;
        }

        //-------------------------------------------------------------------------------
        //组织和打包数据
        //-------------------------------------------------------------------------------
        this.showLoadMask('保存数据，请稍后......');
        this.updateBusiness();                  //处理大结构数据
        this.afterUpdateBusiness();             //调用在处理数据后，post到后台前的空方法
        var postInfo = this.business2JSON();
        
        //-------------------------------------------------------------------------------
        //发出异步请求，保存数据
        //-------------------------------------------------------------------------------
        var theObj = this;
        
        Ext.Ajax.request({
            url: this.postURL,method: 'POST',params: {"dataset":postInfo},
            success: function(action) {
                var getObj = eval('('+action.responseText+')');
                
                theObj.loadMask.hide();
                theObj.clearChangedMarkAfterSuccess();
                theObj.saving = false;
                if(successFunc !=null) {    
                    successFunc.call(this,action,getObj);
                }
                else{
                    if(getObj.dataset.response.success=='true'){
                        //Ext.Msg.alert('系统提示:','数据保存成功！　　　　　　　');
                        if(closeMode=="close")
                            alert("数据保存成功！");
                        else
                            Ext.Msg.alert('系统提示:','数据保存成功！　　　　　　　');
                        
                        if(window.returnValue === undefined)
                            window.returnValue='ok';
                        
                        if(closeMode=="close") window.close();
                    }else{
                        Ext.Msg.alert('系统提示:',getObj.dataset.response.content+'　　　　　　　');
                    }
                }
            },
            failure: function(action) {
                theObj.loadMask.hide();
                //theObj.clearChangedMarkAfterSuccess();
                
                theObj.saving = false;
                if(failureFunc !=null) {
                    failureFunc.call(this,action);
                }else{
                    //alert("提示\n\n保存数据失败！");
                    Ext.Msg.alert('系统提示:','数据保存失败！　　　　　　　');
                    //if(closeMode=="close") window.close();
                }
            }
        });        
    },
    
    //
    
    clearChangedMarkAfterSuccess : function(){
        //debugger;
        for(var i=0;i<this.dataChangedItems.length;i++){
            var w = this.dataChangedItems[i];
            w.delChangedCls();
        }
        
        this.setDataChanged(false);
    },
    
    addChangedItem : function(item){
        for(var i=0;i<this.dataChangedItems.length;i++){
            var w = this.dataChangedItems[i];
            if(w.name==item.name){
                return;
            }
        }
        this.dataChangedItems.push(item);
    },
    
    beforeUpdateBusiness: function(){},
    afterUpdateBusiness : function(){},
    updateBusiness : function(){
        for(var i=0;i<this.children.length;i++){
            var item = this.children[i];
            if(item.dataIndex==undefined || (item.dataIndex instanceof Array)) continue;
            this.setBusinessValue(item.dataIndex,item.getValue());
            if(item.nameIndex!=undefined){
                this.setBusinessValue(item.nameIndex,item.getText());
            }
        }
    },
    
    business2JSON : function(){
        this.saveString = this.businessData.toJSONString();
        return this.saveString;
    },
    
    showSaveString : function(){
        Ext.MessageBox.show({
            title: '保存的数据',
            msg: 'copy出去看。。。',
            width:600,
            closable:false,
            buttons: {cancel : "关闭"},
            prompt:true,
            multiline: true,
            value:this.saveString
        });
    },
    
    checkSaveData : function(){
        var errMsg = [];

        for(var i=0;i<this.children.length;i++){
            var w = this.children[i];
            if(w.needCheck()){
                errMsg.push(w.checkData());
            }
        }
        if(errMsg.length>0){
            var errMsgStr = errMsg.join("");
            if(errMsgStr.length>0){
                Sail.showErrorMessage("数据效验","<table>"+errMsgStr+"</table>","info");
                return false;
            }
        }
        
        return true;
    },
    
    
    
    showLoadMask : function(_msg){
        //var msg = (arguments.length==0)?"保存数据，请稍后......":arguments[1];
        this.loadMask = new Ext.LoadMask(Ext.get(this.getPage().baseDiv),{msgCls:'x-mask-saveing',msg:_msg});
        this.loadMask.show();
    },
    hideLoadMask : function(){
        this.loadMask.hide();
    },
    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 页面业务数据处理相关
    //===================================================================================
    getRequest : function(){
        var request = this.owner.sRequest||{};
        var rData   = request.data||{};

        var a = arguments;
        var findname = (a.length==0)?'id':a[0];
        
        var v = rData[findname];
        return v||"";
    },

    loadData : function(config){
        var o       = this;
 
        //-------------------------------------------------------------
        //-------------------------------------------------------------
        var _url = this.getURL;      //URL
        var gp   = this.getUrlParameter;
        for(var i=0;i<gp.length;i++){
            var v = this.getRequest(gp[i]);
            if(v!="")
                _url+="&"+gp[i]+"="+v;
        }
        
        //-------------------------------------------------------------
        //-------------------------------------------------------------
        var _method = this.method;      //请求类型 GET/POST
        var _scope  = o;                //适用范围
        
        if(config!=undefined && typeof config =='object'){
            _url    = (config.url    != undefined)?config.url:_url;
            _method = (config.method != undefined)?config.url:_method;
            _scope  = (config.scope  != undefined)?config.scope:_scope;
        }
        
        //-------------------------------------------------------------
        //-------------------------------------------------------------
        o.loadOver  = false;
        Sail.request({
            url    : _url,  
            method : _method,   
            scope  : _scope,
            success: function(action,options){
                //debugger;
                o.loadOver = true;

                var _data = eval("("+action.responseText+")"); 
                var flag = o.getSuccessFlag(_data);
                
                if(flag=="true")    
                    options.scope.onLoadDataSuccess(_data,action,options,o);
                else                
                    options.scope.onLoadDataFailure(_data,action,options,o);
                    
            },
            failure: function(action,options){
                //debugger;
                o.loadOver = true;

                var _data = {"dataset":{"response":{"content":"数据获取失败！404错误！","success":"false"}}};
                options.scope.onLoadDataFailure(_data,action,options,o);
            }
        });
    },
 
    onLoadDataSuccess : function(){
        //debugger;
    },
    onLoadDataFailure : function(){
    },

    getSuccessFlag : function(data){
        return Sail.getSubObj(data,this.successFlag);
    },
    
    //===================================================================================
    //方法 ： create something
    //参数 ： void
    //返回 :  void
    //说明 ： 创建页面组件
    //===================================================================================
    createContainerDiv : function(){
        //var lo = this.getBaseLayout();
      
        var bDiv = this.getBaseDiv();
        this.el = Sail.addDiv2(bDiv,{
            className : 'frameContainer_simple',
            id : this.id
        });

        if(this.hidden) this.el.style.display = "none";
    },
    
    
    create : function(){
        this.dataChangedItems = [];
        
        this.createContainerDiv();              //创建页面帧容器层
        
        if(this.beforeCreateWidgets()){
            this.createWidgets();               //创建组件
            this.afterCreateWidgets();          //触发创建后事件

            if(this.bindDataFirst!==false){
                if(this.beforeBindData()){
                    this.bindData2Items();          //绑定数据到组件
                    this.afterBindData();           //触发绑定数据后事件
                }
                            
                if(this.beforeBindEvent()){
                    this.bindEvent2Items();         //绑定事件到组件
                    this.afterBindEvent();          //触发绑定事件后事件
                }
            }else{
                if(this.beforeBindEvent()){
                    this.bindEvent2Items();         //绑定事件到组件
                    this.afterBindEvent();          //触发绑定事件后事件
                }
                if(this.beforeBindData()){
                    this.bindData2Items();          //绑定数据到组件
                    this.afterBindData();           //触发绑定数据后事件
                }
            }
        }
    },

    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 组件创建相关
    //===================================================================================
    beforeCreateWidgets: function(){            //发生在单个页面帧创建组件之前
        return true;
    },
    afterCreateWidgets : function(){            //发生在单个页面帧创建完成之后(绑定之前)
    },
    
    
    //===================================================================================
    //方法 ： createWidgetsByAbsolute
    //参数 ： void
    //返回 :  void
    //说明 ： 当frame对象的layout属性值等于 absolute 时的组件创建
    //        根据指明的绝对位置
    //===================================================================================
    createWidgetsByAbsolute : function(){
        for(var i=0,len=this.items.length;i<len;i++){
            var _wDefine       = this.items[i];
            _wDefine.parentDiv   = this.el;
            _wDefine.ownerGroup = this.children;
            _wDefine.owner     = this;
            _wDefine.widgetPrefix = this.widgetPrefix;
            
            var newWidget = eval("new "+this.widgetPrefix+""+_wDefine.type+"();");
            newWidget.create(_wDefine);
        }
    },
    
    //===================================================================================
    //方法 ： createWidgetsByTable
    //参数 ： void
    //返回 :  void
    //说明 ： 当frame对象的layout属性值等于 table 时的组件创建
    //
    //附属 ： calculateSizeByTable         按照table模式计算尺寸与位置
    //===================================================================================
    createWidgetsByTable : function(){
        
        var cconfig = {
            items : this.items,
            layoutConfig : this.layoutConfig,
            layout : this.layout,
            constructTo : this
        };
        
        if(this.owner.isIframe===true){
            cconfig.padding= {left:0,right:0,top:0,bottom:0};
        }
        //debugger;
        this.layoutC = new Sail.layoutConstructor(cconfig);
        
        this.layoutC.doLayout(this.level);               //20090902 add argument - level
        //debugger;
    },

    //===================================================================================
    //方法 ： createWidgets
    //参数 ： void
    //返回 :  void
    //说明 ： 当frame对象的layout属性值等于 simple 时的组件创建
    //        以此创建，计算位置及尺寸
    //===================================================================================
    createWidgets : function(){
        
         if(this.layout ==='absolute')
            this.createWidgetsByAbsolute();
        else
            this.createWidgetsByTable();
    },


    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 绑定数据到组件相关
    //===================================================================================
    beforeBindData : function(){                //发生于绑定数据到组件之前
        return true;
    },
    afterBindData  : function(){                //发生于绑定数据到组件之后
    },
    bindData2Items : function(){                //绑定数据到组件
        if(this.owner.isList() || this.owner.isSelect()) return;        //2009-08-07 add by yujunjie for spsc
        
        if(this.businessData.dataset!=undefined){
            if(this.owner.isAdd()) return;
            
            for(var i=0;i<this.children.length;i++){
                var child = this.children[i];
                
                if(child.isEnableBindDataItem()===true){
                    child.bindData(this.businessData);
                }
            }
        }else{
            //alert("没有找到页面对应的业务逻辑数据对象的空结构定义！");
        }
    },
    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 绑定事件到组件相关
    //===================================================================================
    beforeBindEvent : function(){               //发生于绑定事件到组件之前
        return true;
    },
    afterBindEvent  : function(){               //发生于绑定事件到组件之后
    },
    bindEvent2Items : function(){
        //alert("绑定事件到组件...");
    },
    
    getItem : function(name){
        for(var i=0;i<this.children.length;i++){
            if(this.children[i].name==name) return this.children[i];
        }
    },
    
    getItemDefine : function(name){
        for(var i=0;i<this.items.length;i++){
            if(this.items[i].name==name) return this.items[i];
        }
    },
    
    getItemByDefine : function(name){
        for(var i=0;i<this.items.length;i++){
            if(this.items[i].name==name) return this.items[i];
        }
    },
    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 页面组件控制相关
    //===================================================================================
    setDataChanged : function(v){
        _BDC.items[this.name]= v||false;
    },


    hide   : function(){
        this.hidden = true;
        this.el.style.display = "none";
    },
    show   : function(){
        this.hidden = false;
        this.el.style.display = "";
    },
    isHide : function(){
        return this.hidden;
    },
    close  : function(){
        window.close();
    }
}

﻿//=======================================================================================
//类名 ： Sail.page
//说明 ： 页面对象
//创建 ： 2009-10-10 16:06:00
//变更 ： 
//
//=======================================================================================

Sail.page = function(config){
    
    //-----------------------------------------------------------------------------------
    //属性
    //-----------------------------------------------------------------------------------
    this.useExt = true;                         //是否使用EXT库支持
    this.id     = "";
    this.name   = "";
    this.title  = "";
    
    this.type   = "page";
    this.mode   = 'list';
    
    this.frames = [];
    this.frameIDIndex = 2008;
    this.alreadyInit = false;
    
    //-----------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------
    this.naviBar = null;
    this.bBarDiv = null;
    this.containerDiv = null;
    
    this.naviBarHeight = 23;
    this.bBarHeight = 23;
    
    this.haveNavi  = true;                     //是否包含导航栏
    this.haveBBar  = false;                    //是否包含页脚栏
    
    this.naviBorder = "0px #0000ff solid";
    this.bbarBorder = false;
    
    this.changedNoMsg = true;
    
    //-----------------------------------------------------------------------------------
    //子对象
    //-----------------------------------------------------------------------------------
    this.baseDiv  = null;                       //缩放基准层、主容器层
    this.baseDivStyle = {
        width : '100%',
        height: '100%',
        zIndex:1,
        //border:'1px #ff0000 solid',
        overflow:"auto",
        paddingLeft : 10,
        paddingTop : 5,
        paddingRight:5,
        paddingBottom : 10
    };
    
    this.sWidth   = 0;                          //当前宽度
    this.sHeight  = 0;                          //当前高度
    
    this.loadMask = null;                       //数据加载ing层  
    this.loadMsgs = [];                         //加载信息列表
    this.loadingText = "加载数据...";
    
    //-----------------------------------------------------------------------------------
    //登录信息
    //-----------------------------------------------------------------------------------
    this.needLoginData = false;                 //是否需要登录信息

    var pathname=location.pathname;
    var ctx="";
    if (pathname.substr(0,1)=="/"){
      ctx=location.pathname.split("/")[1];
    }else{
      ctx=location.pathname.split("/")[0];
    }
    this.url_loginInfo = "/"+ctx+"/DataDict?funcname=basicdata";   //默认的登录信息获取路径
        
    //-----------------------------------------------------------------------------------
    Sail.apply(this,config);
    if(this.isIframe===true){
        this.changeBaseDivStyle();
    }
    this.regist2$();
    //this.init();
}

Sail.page.prototype = {
    
    regist2$ : function(){
        ISR["page"] = this;
    },
    registFrame2$ : function(frameName){
        ISR["items"][frameName]={};
    },

    registFrame2BDC : function(frameName){
        _BDC["items"][frameName]=false;
    },
    
    changeBaseDivStyle : function(){
        this.baseDivStyle.paddingLeft   = 0;
        this.baseDivStyle.paddingTop    = 0;
        this.baseDivStyle.paddingRight  = 0;
        this.baseDivStyle.paddingBottom = 0;
    },
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 页面模式相关操作方法
    //===================================================================================
    haveOperFun : function(funName,tabName){
        return true;
        
        if(this.login.operfun=="" || this.login.operfun==undefined) 
            return false;
            
        var list = ","+this.login.operfun+",";
        var findFun = ","+tabName+"_"+funName+","

        if(list.indexOf(findFun)==-1){
            findFun = ","+funName+",";
            return (list.indexOf(findFun)==-1)?false:true;
        }else{
            return true;
        }
    },

    //haveOperFun : function(){
    //},
    isList : function(){
        return (this.mode=='list')?true:false;
    },
    isSelect : function(){						//2009-08-07 add by yujunjie for spsc
        return (this.mode=='select')?true:false;
    },
    isAdd : function(){
        return (this.mode=='add')?true:false;
    },
    isUpdate : function(){
        return (this.mode=='update')?true:false;
    },
    isView : function(){
        return (this.mode=='view')?true:false;
    },
    setMode : function(mode){
        var modelist = "list,add,update,view";
        if(modelist.indexOf(mode)!=-1){
            this.mode = mode;
        }else{
            alert("设置的不是框架支持的页面模式！");
        }
    },
    getMode : function(){
        return this.mode;
    },
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 工具类 获得部分
    //===================================================================================
    getBaseDiv : function(){
        return this.containerDiv;
    },
    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 工具类
    //===================================================================================
    createFrameID : function(){
        var newID = (this.id=="")?"_"+this.frameIDIndex:this.id+"_"+this.frameIDIndex;
        this.frameIDIndex++;
        return newID; 
    },

    //===================================================================================
    //方法 ： run方法
    //参数 ： void
    //返回 :  void
    //说明 ： Console入口
    //===================================================================================
    getRequest : function(){
        if(arguments.length==0){
            return this.sRequest||{};
        }else if(arguments.length>0){
            return this.sRequest[arguments[0]]||"";
        }else{
        }
    },
    setRequest : function(){
        
        if(this.isIframe===true){
            this.sRequest = Sail.getHrefSearch();
        }else{
            this.sRequest = window.dialogArguments;
            if(this.sRequest !=undefined){
                if(this.sRequest.mode!=undefined){
                    this.mode = this.sRequest.mode;
                }
            }
        }
    },
    init : function(){
        this.setRequest();          //如果存在，处理request信息，变更页面模式
        
        this.frames = (this.frames==undefined)?[]:this.frames;
        this.frames = (this.frames instanceof Array)?this.frames:[this.frames];

        //-------------------------------------------------------------
        //没有明确定义frame时，默认的框架创建一个frame并包含widgets
        //-------------------------------------------------------------
        if(this.frames.length==0){
            this.frames.push({
                name   : "defaultFrame",
                title  : "frame",
                autoLoad : false
            });
        }
        
        for(var i=0;i<this.frames.length;i++){
            if(this.frames[i].id==undefined){           //没有设置frame ID的，创建ID
                this.frames[i].id = this.createFrameID();
            }
            if(this.frames[i].name==undefined){
                this.frames[i].name = "frame"+i;
            }
            if(this.mode=='list' || this.mode=='add'||this.mode=='select'){  //列表和新增页面默认设置为不制动加载数据
                this.frames[i].autoLoad = false;
            }   
            
            this.frames[i].owner = this;                //指明frame所有者 
            
            //if(this.frames[i].layout==undefined) this.frames[i].layout = "simple";
                
            this.frames[i] = new Sail.frame(this.frames[i]);
            this.registFrame2$(this.frames[i].name);
            this.registFrame2BDC(this.frames[i].name);
        }
        this.alreadyInit = true;
    },
    
    //===================================================================================
    //方法 ： run方法
    //参数 ： void
    //返回 :  void
    //说明 ： Console入口
    //===================================================================================
    run : function(){
        this.init();
        
        var o = this;
        //-------------------------------------------------------------
        //不同模式下不同的入口加载方式
        //-------------------------------------------------------------
        if(o.useExt)
            //setTimeout(function(){Ext.onReady(o.run_entryway, o);},50);    
            Ext.onReady(o.run_entryway, o);
        else{
            var o = this;
            document.write("<s"+'cript id="ie-deferred-loader" defer="defer" src="/'+'/:"></s'+"cript>");
            var defer = document.getElementById("ie-deferred-loader");
            defer.onreadystatechange = function(){
                if(this.readyState == "complete"){
                    o.run_entryway();
                }
            };
        }
    },
    delDefer : function(){
        //debugger;
        var defer = document.getElementById("ie-deferred-loader");
        if(defer){
            defer.onreadystatechange = null;
            defer.parentNode.removeChild(defer);
        }
    },
    
    //===================================================================================
    //方法 ： run_entryway
    //参数 ： void
    //返回 :  void
    //说明 ： Console入口
    //===================================================================================
    run_entryway : function(){
        if(!this.useExt) this.delDefer();       //删除入口触发对象
        this.run_initComponent();               //创建
            
        if(this.needLoginData)                  //需要登录信息
            this.run_getLoginInfo();            //获取登录信息
        else{                                   //不需要，则直接跳转到加载页面数据
            if(this.haveNavi===true) this.createNaviBar();
            this.run_loadPageData();
        }
        
        if(this.changedNoMsg===false)
            this.onDataChanged();
    },

    onDataChanged  : function(){
        window.onbeforeunload = this.onbeforeunload;
        //Ext.get(window).on('beforeunload',function(){alert();});
    },
    
    onbeforeunload : function(){
        //debugger;
        var flag = false;
        for(var p in _BDC.items){
            if(typeof _BDC.items[p]!='function'){
                if(_BDC.items[p]===true){
                    flag = true;
                    break;
                }
            }
        }
        
        if(flag===false) return;
            
        var warning = "";
        warning+="\n";

        warning+="┌────────────────────────────────────┐\n";
        warning+="│                           【系统提示信息】                             │      \n";
        warning+="├────────────────────────────────────┤\n";
        warning+="│  在离开该页面前，您修改了数据却没有点击 “保存按钮” 以执行保存操作！  │      \n";
        warning+="│                                                                        │      \n";
        warning+="│  现在请点击下面的“确定”或“取消”按钮以决定接下来的操作。            │      \n";
        warning+="│                                                                        │      \n";
        warning+="│                                                                        │      \n";
        warning+="│  ◆点击“确定”按钮：将继续您的离开操作，已做的数据修改将丢失！！！    │      \n";
        warning+="│                                                                        │      \n";
        warning+="│  ◆点击“取消”按钮：将重新留在当前页面，然后你可以点击相关的“保存”按│      \n";
        warning+="│钮，进行数据保存！！！                                                  │      \n";
        warning+="│                                                                        │      \n";
        warning+="└────────────────────────────────────┘\n";
        //warning+="\n\n";

        return warning;   
    },
    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： Console创建自身
    //===================================================================================
    onScaleDivResize : function(o){
        
        var newWidth = this.getBaseDiv().offsetWidth;
        var newHeight= this.getBaseDiv().offsetHeight;


        var _height = this.baseDiv.offsetHeight-this.baseDivStyle.paddingTop-this.baseDivStyle.paddingBottom;
        _height = (this.haveNavi===true)?(_height-this.naviBarHeight):_height;
        _height = (this.haveBBar===true)?(_height-this.bBarHeight):_height;
        var _width = this.baseDiv.offsetWidth-this.baseDivStyle.paddingLeft-this.baseDivStyle.paddingRight;

        Sail.applyStyle(this.containerDiv,{width:_width,height:_height});

        sdm.push("");
        sdm.push("<font color=red>page resize begin...</font>");
        this.frames[0].layoutC.reLayout({width:_width,height:_height});
        sdm.push("<font color=red>page resize end...</font>");
        sdm.push("");
    },
    
    createScaleBaseDiv : function(){                    //创建基础的、基准的容器层

        //-------------------------------------------------------------
        //-------------------------------------------------------------
        this.baseDiv = Sail.createDiv({id : 'sd_baseScale'});
        Sail.applyStyle(this.baseDiv,this.baseDivStyle);
        this.id = (this.id==undefined)?this.baseDiv.uniqueID+"_page":this.id;
        
        //-------------------------------------------------------------
        // 构造top div
        //-------------------------------------------------------------
        //debugger;
        var _height = this.baseDiv.offsetHeight-this.baseDivStyle.paddingTop-this.baseDivStyle.paddingBottom;
        
        if(this.haveNavi===true){
            this.id_navi = this.id+"_navibar";
            this.naviBar = Sail.addDiv2(this.baseDiv,{id : this.id_navi});
            Sail.applyStyle(this.naviBar,{height:this.naviBarHeight,top:0,border:this.naviBorder});
            _height -=this.naviBarHeight;
        }
        
        //-------------------------------------------------------------
        // 构造 middle Div
        //-------------------------------------------------------------
        _height = (this.haveBBar===true)?(_height-this.bBarHeight):_height;
        this.id_container = this.id+"_container";
        this.containerDiv = Sail.addDiv2(this.baseDiv,{className : 'base_containerDiv',id : this.id_container});

        var _width = this.baseDiv.offsetWidth-this.baseDivStyle.paddingLeft-this.baseDivStyle.paddingRight;

        Sail.applyStyle(this.containerDiv,{width:_width,height:_height,top:20});
        //debugger;
        //-------------------------------------------------------------
        //构造bottom div
        //-------------------------------------------------------------
        if(this.haveBBar===true){
            var _top = _height+(this.haveNavi===true)?this.naviBarHeight:0;
            this.id_bBar = this.id+"_bbar";
            this.bBarDiv = Sail.addDiv2(this.baseDiv,{className : 'base_containerDiv',id : this.id_bBar});
            Sail.applyStyle(this.bBarDiv,{height:this.bBarHeight,top:_top,border:'1 #ff0000 solid'});
            
            if(this.bBar!=undefined){
                var tsc = new Sail.layoutConstructor();
            }
        }


        //-------------------------------------------------------------
        //-------------------------------------------------------------
        this.sWidth = this.baseDiv.offsetWidth;         //记录当前宽度
        this.sHeight= this.baseDiv.offsetHeight;        //记录当前高度
        
        //-------------------------------------------------------------
        //标记更新：暂时使用EXT模式绑定事件，稳定后从EXT中剥离
        //-------------------------------------------------------------
        var o = this;
        Ext.get(this.baseDiv).on('resize',o.onScaleDivResize,o);
    },
    
    createLoadMask : function(){                        //创建数据加载ing层
        this.loadMask = Sail.createDiv({id : 'loading-mask'});
        this.loadMask.innerHTML = "<div id='loading'><div class='loading-indicator'>"+this.loadingText+"</div></div>";
    },
    hideLoadMask : function(){                          //隐藏loadMask
        setTimeout(function(){Ext.get('loading').remove();Ext.get('loading-mask').fadeOut({remove:true});}, 100);
    },
    
    run_initComponent : function(){
        this.createScaleBaseDiv();
        this.createLoadMask();
    },    
    

    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 获取登录信息相关
    //===================================================================================
    createNaviBar : function(){
        var naviText = "";
        if(this.localNaviText!=undefined && this.localNaviText!='')
            naviText = this.localNaviText;
        else
            naviText = (this.login==undefined)?"导航条":((this.login.navi==undefined)?"导航条":this.login.navi);
        
        var o = {        
            "id"             : "ext.label.navi",
            "name"           : "label.navi",
            "type"           : "ext.label",
            "title"          : "<b>"+naviText+"</b>",
            "left"           : 10,
            "top"            : 4,
            "width"          : '100%',
            "height"         : 22,
            "icon"           : true,
            "bold"           : true,
            "iconCls"        : "label_normal",
            "parentDiv"      : this.naviBar
        }
        
        var newWidget = eval("new Sail.widget."+o.type+"();");
        newWidget.create(o);
        
        Ext.get(newWidget.boxDiv.id).on('dblclick',function(){
            //debugger;
        },this);
    },
    beforeLoadLoginInfo : function(){                   //发生于获取登录信息之前
        return true;
    },
    afterLoadLoginInfo : function(){                    //发生于获取登录信息之后
    },
    
    onLoadLoginInfoSuccess: function(dataObj,action,options,scope){     //回调函数：获取登录信息成功
        if(this.haveNavi===true) this.createNaviBar();
        
        this.afterLoadLoginInfo();       
        this.run_loadPageData();
    },
    onLoadLoginInfofailure: function(dataObj,action,options,scope){     //回调函数：获取登录信息失败
        alert("获取登录信息失败！");
    },
    
    getOperfun     : function(){    return this.login.operfun;      },
    getFactoryName : function(){    return this.login.factoryName;  },
    getFactoryID   : function(){    return this.login.factoryID;    },
    getOpername    : function(){    return this.login.opername;     },
    getOpertype    : function(){    return this.login.opertype;     },
    getOperorgid   : function(){    return this.login.operorgid;    },
    getOperorgname : function(){    return this.login.operorgname;  },
    getOpercode    : function(){    return this.login.opercode;     },

    getUser        : function(){    return this.login.operator      },
    getUserName    : function(){    return this.login.opername;     },
    getUserCode    : function(){    return this.login.opercode;     },
    getLogin       : function(){    return this.login;              },    
    
    run_getLoginInfo : function(){                      //获取登录信息主方法
        var o = this;
        
        if(this.beforeLoadLoginInfo()){
            this.login = new Sail.loginInfo({
                url   : o.url_loginInfo,      //设置请求URL
                scope : o
            });
            
            this.login.getLoginInfo();        //请求登录信息
        }
    },

    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 加载页面数据相关
    //===================================================================================
    beforeLoadData : function(){                        //发生于加载页面数据之前
        return true;
    },
    afterLoadData : function(){                         //发生于加载页面数据之后
        return true;
    },

    onLoadDataSuccess : function(dataObj,action,options,scope){         //回调函数： 获取成功
        //-------------------------------------------------------------
        var oPage = scope;
        Sail.apply(oPage.businessData,dataObj);
        
        //-------------------------------------------------------------
        //遍历所有页面数据是否加载完毕
        //-------------------------------------------------------------
        if(this.allFrameLoadOver()){                    //如果加载完毕(所有页面)
            if(this.afterLoadData())                    //转移处理方法
                this.run_createFrames();                //创建页面   
        }
    },
    onLoadDataFailure : function(dataObj,action,options,scope){         //回调函数： 获取失败
        //debugger;
        var info = ""+(scope.title||scope.name)+"页面加载数据失败！\n错误信息："+this.getErrorMsg(dataObj);
        alert(info);
        return;
        
        //-------------------------------------------------------------
        //遍历所有页面数据是否加载完毕
        //-------------------------------------------------------------
        if(this.allFrameLoadOver()){                    //如果加载完毕
            if(this.afterLoadData())                    //转移处理方法
                this.run_createFrames();                //创建页面
        }
    },

    allFrameLoadOver : function(){                      //判断是否所有frame数据都加载完毕
        for(var i=0;i<this.frames.length;i++){
            if(!this.frames[i].loadOver) return false;
        }
        return true;
    },
    allFramePauseLoad : function(){                     //判断是否所有frame都不需要自动加载数据
        for(var i=0;i<this.frames.length;i++){
            if(this.frames[i].autoLoad) return false;
        }
        return true;
    },
    getErrorMsg : function(o){                          //获取加载失败信息
        return o.dataset.response.content;
    },

    run_loadPageData : function(){                      //加载页面数据主方法
        var o = this;
        
        if(this.beforeLoadData()){

            //---------------------------------------------------------
            //所有frame都不需要自动加载数据，则直接跳转到创建页面
            //---------------------------------------------------------
            if(this.allFramePauseLoad()){
                this.afterLoadData();                   //转移处理方法
                this.run_createFrames();                //创建页面
                return;
            }
        
            //---------------------------------------------------------
            //
            //---------------------------------------------------------
            for(var i=0;i<this.frames.length;i++){       //遍历所有页面
                
                if(this.frames[i].autoLoad){             //如果页面属性设置为自动加载
                    this.frames[i].loadData({scope:o});  //则调用相关方法加载数据
                }else{
                    this.frames[i].loadOver = true;      //认为完成一次空加载
                }
            }
        }
    },

    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： frames create 处理相关
    //===================================================================================
    beforeCreateFrames : function(){                    //发生于创建页面帧之前
        return true;
    },
    afterCreateFrames : function(){                     //发生于创建页面帧之后
    },
    
    run_createFrames : function(){                      //创建所有的页面帧
        
        //this.run_over();        
        //return;
        if(this.beforeCreateFrames()){
            for(var i=0;i<this.frames.length;i++){
                this.frames[i].create();
            }
            this.afterCreateFrames();
            this.run_over();        
        }
        
    },

    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： run over 处理相关
    //===================================================================================
    afterRun : function(){
    },
    
    run_over : function(){
        this.afterRun();
        this.hideLoadMask();
        //alert("load over...");
    },
    
    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： frames 处理相关
    //===================================================================================
    getFrame    : function(value){
        if(typeof value =="number")
            return this.frames[value];
        else if(typeof value =="string"){
            for(var i=0;i<this.frames.length;i++)
                if(this.frames[i]["name"]==value)
                    return this.frames[i];
        }
        return {};
    },
    addFrame    : function(frameConfig){
        
    },

    removeFrame : function(value){
    },
    removeAll  : function(){
    },
    showFrame   : function(){
    },
    hideFrame   : function(){
    },
    hideAll    : function(){
    }
}

﻿//=======================================================================================
//类名 ： Sail.widget
//说明 ： 组件基类
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================

Sail.widget = function(config){
    this.id;
    this.type;
    this.name;
    this.title;

    this.level;
    
    //-----------------------------------------------------------------------------------
    //this.zIndex = 10;
    this.defaultWidth = 100;
    //this.defaultHeight= 24;
    //-----------------------------------------------------------------------------------
    this.created = false;
    
    //-----------------------------------------------------------------------------------
    //this.parentDiv  = null;         //父容器对象
    //this.ownerGroup = null;         //组件组对象
    //this.el         = null;         //组件实体对象
    //this.container  = null;         //封装容器对象 
    //this.items      = null;         //组件子元素
    
    //-----------------------------------------------------------------------------------
    Sail.apply(this, config);
    if(this.name==undefined) this.name=this.title;
    this.initComponent();
}

Sail.extend(Sail.widget, Ext.util.Observable, {
//Sail.widget.prototype = {
    
    initComponent : function(){
        this.name = this.name || this.title;
    },
    haveCreated : function() { return this.created;    },

    isEnableBindDataItem : function(){
        return this.enableBindData;
    },
    
    getBusiness : function(){
        return this.ownerFrame.businessData||null;
    },
    
    //===================================================================================
    //方法 ： override some check data
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    needCheck : function(){
        if(this.enableBindData===true&&this.allowBlank===false){
            return true;
        }else{
            return false;
        }
    },
    
    checkData : function(){
        var value  = this.el.getValue();
        var flag   = this.el.validateValue(value);
        if(!flag){
            return this.getCheckErrorMsg();
        }else{
            return "";
        }
    },
    
    getCheckErrorMsg : function(){
        var _title = ((this.title==undefined || this.title=="")?this.name:this.title);
        
        var formatInfo = this.getFormatInfo();
        
        var ra = [];
        ra.push("<tr style='font:normal 12px verdana;'>");
        ra.push("<td align=right nowrap style='color:#ff0000'>"+_title+"</td>");
        ra.push("<td>&nbsp;数据效验错误！&nbsp;&nbsp;</td>");
        ra.push("<td style='color:#ff0000'>该数据要求：<font color=black>"+formatInfo+"</td>");
        ra.push("</tr>");
        
        return ra.join("");
    },
    
    getFormatInfo : function(){
        var formatStr = "";
        if(this.minLength !=undefined) formatStr+="最小长度为"+this.minLength+"，";
        
        if(this.maxLength !=undefined&&this.type=='textArea') formatStr+="最大长度为"+this.maxLength+"，";
        
        if(this.minValue  !=undefined) formatStr+="最小值为"+this.minValue+"，";
        if(this.maxValue  !=undefined) formatStr+="最大值为"+this.maxValue+"，";
        
        if(this.allowBlank !=undefined)       formatStr+="不能为空，";
        if(this.allowDecimals !=undefined)    formatStr+="不能为小数，";
        if(this.allowNegative !=undefined)    formatStr+="不能为负数，";
        if(this.decimalPrecision !=undefined) formatStr+="小数位数为"+this.decimalPrecision+"，";
        
        return formatStr.left(formatStr.length-1)+"。";
    },
    
    //===================================================================================
    //方法 ： some functions for get...
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getLeft     : function() { return this.left;   },
    getTop      : function() { return this.top;    },
    getRight    : function() { return this.left+this.width;  },
    getBottom   : function() { return this.top+this.height;  },
    
    getWidth    : function() { return this.width;  },
    getHeight   : function() { return this.height; },

    getID       : function() { return this.id;     },
    getTitle    : function() { return this.title;  },
    getType     : function() { return this.type;   },
    getName     : function() { return this.name;   },

    getParent   : function() { return this.parentDiv; },
    getGroup    : function() { return this.ownerGroup;},
    getContainer: function() { return this.container; },

    getOCD      : function() { return this.container.getEl(); },
    
    getSearch   : function(){
        var _search = [];
        var v = this.getValue();
        var f = "";
        
        if(this.dataIndex!=undefined){
            if(this.dataIndex instanceof Array){
                for(var i=0;i<this.dataIndex.length;i++){
                    f=this.dataIndex[i];
                    if(v[f]!=-1 && v[f]!="" && v){
                        var tv = v[f];
                        _search.push("&");
                        _search.push(f);
                        _search.push("=");
                        _search.push(encodeURI(tv));
                    }
                }
            }else{
                f=this.dataIndex;
                if(v!=-1 && v!="" && v){
                    _search.push("&");
                    _search.push(f);
                    _search.push("=");
                    _search.push(encodeURI(v));
                }
            }
        }   
        return _search.join('');
    },
    
    getIntendingHeight : function(){
        //if(this.type=='tree') debugger;
        return (this.defaultHeight==undefined)?100:this.defaultHeight;
    },
    
    //===================================================================================
    //方法 ： some functions for place and size...
    //参数 ： void
    //返回 :  
    //说明 ： 
    //===================================================================================
    setTop    : function(t){ this.container.setTop(t);   this.top    = t; },
    setLeft   : function(l){ this.container.setLeft(l);  this.left   = l; },
    setRight  : function(r){ this.setLeft(r-this.width); },
    setBottom : function(b){ this.setTop(b-this.height); },

    setWidth : function(w){
        this.width = w;
        this.container.setWidth(w);
        if(this.el!=undefined && this.el.setWidth!=undefined){
            this.el.setWidth(w);
        }
    },
    setHeight:function(h){
        this.height = h;
        this.container.setHeight(h);
        this.el.setHeight((this.type=='ext.myForm')?h-20:h);
    },

    setSize : function(w,h){
        this.setHeight(h);
        this.setWidth(w);
    },
    
    setCheck : function(config){
        Sail.apply(this,config);
        Sail.apply(this.el,config);
        var flag   = this.el.validateValue(this.el.getValue());
        
        if(flag){
            this.el.el.removeClass(this.el.invalidClass);
        }else{
            this.el.el.addClass(this.el.invalidClass);            
        }
    },
    
    move2 : function(l,t){
        this.setLeft(l);    this.setTop(t);
    },
   
    //===================================================================================
    //方法 ： some functions for control...
    //参数 ： void
    //返回 :  
    //说明 ： 
    //===================================================================================
    hide : function(){  this.container.hide();    },
    show : function(){  this.container.show();    },
    
    enable : function(){},
    disable: function(){},
    
    //===================================================================================
    //方法 ： about event...
    //参数 ： void
    //返回 :  
    //说明 ： 
    //===================================================================================
    //on : function(eventName, handler, scope, options){
    //    debugger;
    //    this.el.on(eventName, handler, scope, options);
    //},
    
    //===================================================================================
    //方法 ： some functions for create...
    //参数 ： void
    //返回 :  
    //说明 ： 
    //===================================================================================
    createContainer : function(){
        this.left  = (this.left  ==undefined)?0:this.left;
        this.top   = (this.top   ==undefined)?0:this.top;
        this.width = (this.width ==undefined)?this.defaultWidth:this.width;
        this.height= (this.height==undefined)?this.defaultHeight:this.height;

        this.container = new Sail.DIV({
            left  : this.left,
            top   : this.top,
            width : this.width,
            height: this.height,
            //border : "1px #0000ff solid",
            parent: this.parentDiv
        });
    },
    
    beforeCreateWidget : function(){},
    afterCreateWidget  : function(){},
    createWidgetElement: function(){},

    dealWithDeferEvents : function(){
        if(sys_deferEvents[this.name]!=undefined){

            var info = sys_deferEvents[this.name];
            if(info.funcName==='getButton'){
                //debugger;
                var w = this[info.funcName].call(this,info.btName);
                var scope = (typeof info.scope =='object')?info.scope:(info.scope==undefined)?null:$(info.scope);
                
                if(scope && scope.isSimulant===true) scope = $(scope.name);
                w.on(info.eName,info.handler,scope);
            }else if(info.funcName=="addAction"){
                this.addAction(info.actionName,info.handler,info.scope);
            }
        }
    },
    
    create : function(config){
        Sail.apply(this,config);

        if(this.ownerGroup!=undefined)  this.ownerGroup.push(this);     //添加组件到管理组
        this.created = true;

        if(this.page&& this.page.isView()){
            this.readOnly=true;
        }
        
        this.beforeCreateWidget();      //创建组件之前预留处理方法
        this.createContainer();         //创建组件容器
        this.createWidgetElement();     //创建组件实体展现
        this.afterCreateWidget();       //创建组件之后预留处理方法

        this.dealWithDeferEvents();     //20090914215100 add for defer bind event 2 items for tabs 
        
        return this;
    }
});




Sail.widget.ext = Sail.extend(Sail.widget,{});








﻿//=======================================================================================
//类名 ： Sail.widget.boxComponent
//说明 ： 编辑器输入选择类组件基类
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================


Sail.widget.boxComponent = Sail.extend(Sail.widget,{
    defaultHeight : 22,
    
    mustMark : "<font color=#ff0000>*</font>", 
    
    colonChar: "：",        //冒号分隔符
    colonWidth: 12,         //冒号分隔符占据的宽度
    
    haveColon : true,       //是否包含冒号分隔符，默认值为true
    showTitle : true,       //是否显示标题
    
    inputMinWidth : 16,     //输入框最小宽度
    titleMinWidth : 32,     //文本显示最小宽度(私有，不对外公开)
    
    titleScale    : 0.4,    
    
    textOverflow : false,   //标记标题是否发生折叠
    
    
    //===================================================================================
    //方法 ： override some functions
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setWidth : function(w){        
        this.width = w;
        this.container.setWidth(w);
        
        this.refresh();
    },
    setHeight:function(h){
    },
    enable : function(){
        if(this.titleDiv!=undefined)
            this.titleDiv.applyStyle({color:(this.textColor==undefined)?'#000000':this.textColor})
        if(this.colonDiv!=undefined)
            this.colonDiv.applyStyle({color:(this.textColor==undefined)?'#000000':this.textColor})
        
        this.disabled = false;
        if(this.el.enable!=undefined)
            this.el.enable();
    },
    disable : function(){
        if(this.titleDiv!=undefined)
            this.titleDiv.applyStyle({color:'#a0a0a0'})
        if(this.colonDiv!=undefined)
            this.colonDiv.applyStyle({color:'#a0a0a0'})

        this.disabled = true;
        if(this.el.disable!=undefined)
            this.el.disable();
    },
    getValue : function(){
        if(this.el.getValue!=undefined)
            return this.el.getValue();
    },
    setValue : function(v){
        if(this.el.setValue!=undefined)
            this.el.setValue(v);
    },
    enableUseScale : function(){
        var w = this.width-this.width*this.titleScale-this.colonWidth;
        return (w<this.inputMinWidth)?0:this.width*this.titleScale;
    },

    bindData : function(bd){
        if(bd==undefined) 
        bd = this.getBusiness();
        

        if(this.dataIndex!=undefined){
            var v = Sail.getSubObj(bd,this.dataIndex);
            this.setValue(v);
        }else{
            //alert("组件="+this.name+",类别="+this.type+",在执行数据绑定时，没有找到dataIndex定义！");
        }
    },
    
    focus : function(){
        if(this.el && this.el.focus){
            this.el.focus();
        }
    },
    on : function(eventName, handler, scope, options){
        if(eventName=='enterpress'){
            this.el.on('specialkey',function(field,e){
                if(e.getKey()==e.ENTER){
                    handler.call(this,field,field.getValue());
                }
            },scope,options);
            
        }else{
            this.el.on(eventName, handler, scope, options);
        }
    },
    //===================================================================================
    //方法 ： override some functions
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setTitle : function(t){
        //alert(this.title+","+this.name+","+this.id);
        this.title=this.name=t;
        this.refresh();
    },
    refresh : function(){
        if(this.showTitle!==true){ 
            if(this.el)
                this.el.setWidth(this.width);
            return;
        }

        this.createTitleEl();

        var begin = (this.titleWidth==undefined)?0:this.titleWidth+((this.colonWidth==undefined)?0:this.colonWidth);
        this.boxWidth = this.width - begin;
        
        this.boxDiv.setLeft(begin);
        this.boxDiv.setWidth(this.boxWidth);
        
        if(this.el.setWidth!=undefined){
            if(this.type=='textArea')
                this.el.setWidth(this.boxWidth-3);
            else
                this.el.setWidth(this.boxWidth);
        }
    },
    
    //===================================================================================
    //方法 ： create somethings
    //参数 ： 
    //返回 :  
    //说明 ： createTitleEl、createColon、createTitleEl、createElStructure
    //===================================================================================
    setChangedCls : function(){
        //debugger;
        if(this.titleDiv!=undefined){
            this.titleDiv.addClass('icon-datachanged');
        }else{
            this.owner.setChangedCls();
        }
    },
    delChangedCls : function(){
        if(this.titleDiv!=undefined){
            this.titleDiv.removeClass('icon-datachanged');
        }else{
            this.owner.delChangedCls();
        }
    },
    
    createTitleEl : function(){
        var ocd = this.getOCD();
        
        //-------------------------------------------------------------------------------
        //构造标题
        //-------------------------------------------------------------------------------
        var firstFlag = false;
        if(this.titleDiv==undefined){
            var c = {
                parent: ocd,
                style : {left: 0,top: 4,paddingLeft:6,border:'0px #ff0000 solid',cursor:"default"}
            };
            c.style.color = (this.textColor==undefined)?"#000000":this.textColor;
            this.titleDiv = new Sail.DIV(c);
            firstFlag = true;
        }else{
            var _style={width:0};
            if(this.textOverflow){ 
                _style.cursor = 'default';
                _style.textOverflow ='clip'; 
                this.textOverflow = false; 
            }
            this.titleDiv.applyStyle(_style);
        }

        var mustTitle = this.mustMark+this.title;
        //var mustTitle = "<font color='#ff0000'>"+this.title+"</font>";
        
        var _title = (this.allowBlank===false && this.isUnited!==true)?mustTitle:this.title;
        Sail.apply(this.titleDiv.el,{innerHTML:_title,align:"left",noWrap:true});
        
        var actWidth = (firstFlag)?this.titleDiv.getOffset().width:this.titleDiv.getScroll().width;

        //-------------------------------------------------------------------------------
        //如果标题宽度大于标题可用宽度，则折叠标题
        //-------------------------------------------------------------------------------
        var titleMaxWidth = this.width-this.colonWidth-this.inputMinWidth;
        titleMaxWidth=(titleMaxWidth<=0)?this.titleMinWidth:titleMaxWidth;
        
        if(actWidth>titleMaxWidth){
            var tw = this.enableUseScale();
            this.titleDiv.applyStyle({cursor:'help',overflow:"hidden", textOverflow:"ellipsis",  width:(tw==0)?titleMaxWidth:tw});
            this.titleDiv.setHTML("<noBR>"+_title+"</noBR>");
            this.textOverflow = true;
            
            if(this.tip==undefined){
                this.tip = new Ext.ToolTip({
                    target: this.titleDiv.el,width:actWidth,html: _title,trackMouse:true
                });
            }else{
                this.tip.width = actWidth;
                this.tip.html = _title;
            }
        }
        else{
            if(!firstFlag){
                if(this.tip!=undefined){
                    this.tip.destroy();
                    this.tip=null;
                }
            }
            this.titleDiv.setWidth(actWidth);
        }
            
        this.titleWidth = parseInt(this.titleDiv.getWidth().replace('px',''),10);
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.haveColon===true){
            this.crateColon(this.titleWidth);
        }
    },
    
    crateColon : function(begin){
        var ocd = this.getOCD();
        
        if(this.colonDiv==undefined){
            this.colonDiv = new Sail.DIV({
                parent: ocd,
                style : {color:(this.textColor==undefined)?'#000000':this.textColor,left: begin,top: 6,border:'0px #ff0000 solid',cursor:"default"}
            });
            Sail.apply(this.colonDiv.el,{innerHTML:this.colonChar,align:"left",noWrap:true});
        }else{
            this.colonDiv.setLeft(begin);
        }
        
        this.colonWidth = this.colonDiv.getOffset().width;
    },
    
    createElBox : function(){
        var begin = (this.titleWidth==undefined)?0:this.titleWidth+((this.colonWidth==undefined)?0:this.colonWidth);
        
        this.boxWidth = this.width - begin;
        
        var ocd = this.getOCD();
        this.boxDiv = new Sail.DIV({
            parent: ocd,
            style : {
                left: begin,top: 0,width:this.boxWidth,height:22,
                border:'0px #ff0000 solid',cursor:"default"}
        });
        
        return this.boxDiv.el;
    },
    
    createElStructure : function(){
        if(this.showTitle===true)
            this.createTitleEl();                       //创建标题 el
            
        return this.createElBox();
    },
    
    //===================================================================================
    //方法 ： override some functions
    //参数 ： 
    //返回 :  
    //说明 ： 创建展现结构
    //===================================================================================
    afterCreateWidget : function(){
        if(this.page.mode!=='list'){
            if(this.dataIndex!=undefined){
                this.on('change',function(){
                    this.setChangedCls();
                    this.ownerFrame.addChangedItem(this); 
                    this.ownerFrame.setDataChanged(true);
                },this);
            }
        }

        if(this.disabled===true)
            this.disable();
        
        if(this.value!=undefined && this.value!='')
            this.setValue(this.value);            
    }
});




//=======================================================================================
//类名 ： Sail.widget.boxComponent
//说明 ： 编辑器输入选择类组件
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================
Sail.widget.ext.input = Sail.extend(Sail.widget.boxComponent,{
    enableBindData      : true,
    createWidgetElement : function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config ={width:this.boxWidth,renderTo:box};

        if(this.readOnly!=undefined)    _config.readOnly    = this.readOnly;
        if(this.minLength!=undefined)   _config.minLength   = this.minLength;
        if(this.maxLength!=undefined)   _config.maxLength   = this.maxLength;
        if(this.allowBlank!=undefined)  _config.allowBlank  = this.allowBlank;

        if(this.regex !=undefined) _config.regex = this.regex;
        //_config.msgTarget = 'side';
        if(this.inputType!=undefined) _config.inputType = this.inputType;
        
        //_config.inputType="password";
        this.el = new Ext.form.TextField(_config);        
        //this.el.focus();
        if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
    }
});

Sail.widget.ext.inputHaveButton = Sail.extend(Sail.widget.boxComponent,{
    enableBindData      : true,

    createElBox : function(){
        var begin = (this.titleWidth==undefined)?0:this.titleWidth+((this.colonWidth==undefined)?0:this.colonWidth);
        
        this.boxWidth = this.width - begin-76;
        
        var ocd = this.getOCD();
        this.boxDiv = new Sail.DIV({
            parent: ocd,
            style : {
                left: begin,top: 0,width:this.boxWidth,height:22,
                border:'0px #ff0000 solid',cursor:"default"}
        });
        
        begin = begin+this.boxWidth;
        this.buttonDiv = new Sail.DIV({
            parent: ocd,
            style : {
                left: begin,top: 3,width:76,height:20,
                border:'0px #ff0000 solid',cursor:"default"}
        });
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.buttonDiv.el.id = this.buttonDiv.el.uniqueID;
        this.buttonDivID = this.buttonDiv.el.id;
        
        this.id_btLeftTop   = this.buttonDivID+"_leftTop";
        this.id_btLeft      = this.buttonDivID+"_left";
        this.id_btRight     = this.buttonDivID+"_right";
        this.id_btRightTop  = this.buttonDivID+"_rightTop";

        this.buttonDiv.setHTML(this.getButtonDivHTML());
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        Ext.get(this.id_btLeftTop).on('mouseover',  function(){Ext.get(this.id_btLeftTop).addClass('ihb_leftTop2');},this);
        Ext.get(this.id_btLeftTop).on('mouseout',   function(){Ext.get(this.id_btLeftTop).removeClass('ihb_leftTop2');},this);
        Ext.get(this.id_btLeft).on('mouseover',     function(){Ext.get(this.id_btLeft).addClass('ihb_left2');},this);
        Ext.get(this.id_btLeft).on('mouseout',      function(){Ext.get(this.id_btLeft).removeClass('ihb_left2');},this);

        Ext.get(this.id_btRight).on('mouseover',    function(){Ext.get(this.id_btRight).addClass('ihb_right2');},this);
        Ext.get(this.id_btRight).on('mouseout',     function(){Ext.get(this.id_btRight).removeClass('ihb_right2');},this);
        Ext.get(this.id_btRightTop).on('mouseover', function(){Ext.get(this.id_btRightTop).addClass('ihb_rightTop2');},this);
        Ext.get(this.id_btRightTop).on('mouseout',  function(){Ext.get(this.id_btRightTop).removeClass('ihb_rightTop2');},this);

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        Ext.get(this.id_btLeftTop).on('click',  function(){this.onLeftTopClick();},this);
        Ext.get(this.id_btLeft).on('click',     function(){this.onLeftClick();},this);
        Ext.get(this.id_btRight).on('click',    function(){this.onRightClick();},this);
        Ext.get(this.id_btRightTop).on('click', function(){this.onRightTopClick();},this);

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        return this.boxDiv.el;
    },
    
    onLeftTopClick : function(){},
    onLeftClick : function(){},
    onRightClick : function(){},
    onRightTopClick : function(){},
    
    getButtonDivHTML : function(){
        var sb = new Sail.stringBuffer();

        sb.push("<table style='cursor:hand' border=0 cellspacing=0>");
        sb.push("<tr height=23>");
        sb.push("<td id='"+this.id_btLeftTop+"' class='ihb_leftTop'  width='16'></td>");
        sb.push("<td width='2'></td>");
        sb.push("<td id='"+this.id_btLeft+"' class='ihb_left'     width='16'></td>");
        sb.push("<td width='8'></td>");
        sb.push("<td id='"+this.id_btRight+"' class='ihb_right'    width='16'></td>");
        sb.push("<td width='2'></td>");
        sb.push("<td  id='"+this.id_btRightTop+"' class='ihb_rightTop' width='16'></td>");
        sb.push("</tr></table>");

        return sb.toString();
    },
    
    createElStructure : function(){
        if(this.showTitle===true)
            this.createTitleEl();                       //创建标题 el
            
        return this.createElBox();
    },
    
    createWidgetElement : function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config ={width:this.boxWidth,renderTo:box};

        if(this.readOnly!=undefined)    _config.readOnly    = this.readOnly;
        if(this.minLength!=undefined)   _config.minLength   = this.minLength;
        if(this.maxLength!=undefined)   _config.maxLength   = this.maxLength;
        if(this.allowBlank!=undefined)  _config.allowBlank  = this.allowBlank;

        this.el = new Ext.form.TextField(_config);        
        //this.el.focus();
        if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
    }
});

Sail.widget.ext.numInput = Sail.extend(Sail.widget.boxComponent,{
    enableBindData : true,
    createWidgetElement:function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config ={width:this.boxWidth,renderTo:box};
        
        if(this.readOnly  !=undefined)  _config.readOnly     = this.readOnly;
        if(this.minLength !=undefined)  _config.minLength    = this.minLength;
        if(this.maxLength !=undefined)  _config.maxLength    = this.maxLength;
        if(this.minValue  !=undefined)  _config.minValue     = this.minValue;
        if(this.maxValue  !=undefined)  _config.maxValue     = this.maxValue;

        if(this.allowBlank !=undefined)         _config.allowBlank      = this.allowBlank;
        if(this.allowDecimals !=undefined)      _config.allowDecimals   = this.allowDecimals;
        if(this.allowNegative !=undefined)      _config.allowNegative   = this.allowNegative;
        if(this.decimalPrecision !=undefined)   _config.decimalPrecision= this.decimalPrecision;

        if(this.regex !=undefined) _config.regex = this.regex;
        
        //_config.msgTarget = 'side';
        this.el = new Ext.form.NumberField(_config);        
        //this.el.focus();

        if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
    }
});

Sail.widget.ext.timeInput = Sail.extend(Sail.widget.boxComponent,{
    enableBindData      : true,
    
    createWidgetElement:function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config ={width:this.boxWidth,renderTo:box};
        this.maxLength = 8;
        
        if(this.readOnly  !=undefined)  _config.readOnly    = this.readOnly;
        if(this.allowBlank!=undefined)  _config.allowBlank  = this.allowBlank;
        if(this.maxLength !=undefined)  _config.maxLength   = this.maxLength;
    
        this.el = new Ext.form.timeField(_config);        

        if(this.maxLength!=undefined) this.el.el.dom.maxLength = 8;
    }
});

Sail.widget.ext.textArea = Sail.extend(Sail.widget.boxComponent,{
    enableBindData : true,
    
    align : 'horizontal',    //vertical
    
    setHeight : function(h){
        this.height = h;
        this.container.setHeight(h);
        if(this.el.setHeight!=undefined)
            this.el.setHeight(h);
    },
    
    //===================================================================================
    //方法 ： override createWidgetElement
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createWidgetElement:function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config ={width:this.boxWidth-3,renderTo:box};

        if(this.readOnly!=undefined)    _config.readOnly    = this.readOnly;
        if(this.minLength!=undefined)   _config.minLength   = this.minLength;
        if(this.maxLength!=undefined)   _config.maxLength   = this.maxLength;
        if(this.allowBlank!=undefined)  _config.allowBlank  = this.allowBlank;
        if(this.inputType!=undefined)   _config.inputType   = this.inputType;
        
        if(this.height!=undefined)      _config.height      = this.height;

        this.el = new Ext.form.TextArea(_config);        
        //this.el.focus();
        
        if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
        
    }
});


Sail.widget.ext.checkGroup2 = Sail.extend(Sail.widget.boxComponent,{
});

Sail.widget.ext.combox = Sail.extend(Sail.widget.boxComponent,{
    enableBindData : true,
    readOnly : true,
    mode     : 'local',
    
    bindData : function(bd){
        if(bd==undefined) 
        bd = this.getBusiness();
        
        if(this.dataIndex!=undefined){
            var t = "";
            if(this.nameIndex!=undefined){
                t = Sail.getSubObj(bd,this.nameIndex);
                this.setText(t);
            }
            var v = Sail.getSubObj(bd,this.dataIndex);
            this.el.value=v;
            this.el.el.removeClass(this.el.invalidClass);
            
            //this.setValue(v);
            this.el.fireEvent('aftersetvalue',this.el,{},t,v);

        }else{
            //alert("组件="+this.name+",类别="+this.type+",在执行数据绑定时，没有找到dataIndex定义！");
        }
    },
    getStore : function(){
        return this.el.store;
    },
    
    getJSONData : function(){
        return this.getStore().reader.jsonData;
    },
    
    getText : function(){
        return this.el.el.dom.value;
    },
    setText : function(t){
    	this.el.el.dom.value=t;
    	this.el.lastSelectionText = t;
        this.el.el.removeClass("x-form-empty-field");    	
    },
    clear : function(){
        this.value="";
        this.setValue("");
        this.el.store.removeAll();
    },
    on : function(eventName, handler, scope, options){
        if(eventName=='datachanged'){
            this.el.store.on(eventName, handler, this.el, options);
        }else if(eventName=='afterload'){
            this.el.store.on('datachanged', handler, this.el, options);
        }else if(eventName=='select' || eventName=='beforeselect'){
            
            this.el.on(eventName, function(combo,record,index){
                var text  = record.get(this.fieldText);
                var value = record.get(this.fieldValue);
                return handler.call(this,combo,record,index,text,value);
            }, this, options);
            
        }else{
            this.el.on(eventName, handler, scope, options);
        }
    },

    //===================================================================================
    //方法 ： load
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    load : function(){
        var _root,_textField,_valueField,_fields=[];
        var a =arguments;
        
        
        if(a.length==0){
            return;
        }else if(a.length==1){
            _url = a[0];

            _root       = this.root;
            _textField  = (this.fieldText) ?this.fieldText :"text";
            _valueField = (this.fieldValue)?this.fieldValue:"code";
            _fields.push(_textField);
            _fields.push(_valueField);

            if(this.otherFields!=undefined){
               _fields = _fields.concat(this.otherFields);
            }
            
            this.fieldText  = _textField;
            this.fieldValue = _valueField;
        }else if(a.length==2){
            _url = a[0];

            var config  = a[1];
            _root       = (config.root)?config.root:this.root;
            _textField  = (config.fieldText)?config.fieldText:this.fieldText;
            _valueField = (config.fieldValue)?config.fieldValue:this.fieldValue;

            _fields.push(_textField);
            _fields.push(_valueField);

            if(config.otherFields!=undefined){
               _fields =  _fields.concat(config.otherFields);
               this.otherFields = [].concat(config.otherFields);
            }
            
            this.fieldText = _textField;
            this.fieldValue = _valueField;
        }
        
        //this.value="";
        //this.el.value='';
        //this.el.el.dom.value='未选择...';
        
        this.enable();
        
        if(this.el.store==null){
            this.el.store = new Ext.data.Store();
        }
        this.setValue("");
        
        this.el.store.removeAll();
        this.el.store.proxy= new Ext.data.HttpProxy({url: _url, method: 'POST'});
	    this.el.store.reader= new Ext.data.JsonReader({root: _root}, _fields);

        this.el.valueField   = this.fieldValue;        
        this.el.displayField = this.fieldText;      
        this.el.store.load();

        if(this.autoSelectFirst===true){
            this.el.store.on('datachanged',this.selectFirst,this);
        }
        
    },
    
    selectFirst : function(store){
        var record = store.getAt(1);
        if(record){
            var value = record.get(this.fieldValue);
            this.setValue(value);
        }
    },
    
    selectAppointedRecord : function(store){
        if(typeof this.autoSelectRecord=='number'){
            var record = store.getAt(this.autoSelectRecord);
            if(record){
                this.setValue(record.get(this.fieldValue));
            }
        }else if(typeof this.autoSelectRecord=='function'){
            for(var i=0;i<store.getCount();i++){
                var record = store.getAt(i);
                if(this.autoSelectRecord.call(this,record)==true){
                    this.setValue(record.get(this.fieldValue));
                }else{
                }
            }
        }else{
        }
    },
    //===================================================================================
    //方法 ： override createWidgetElement
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createWidgetElement:function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var _fields     = [];
        var _textField  = (this.fieldText !=undefined)?this.fieldText :"text";
        var _valueField = (this.fieldValue!=undefined)?this.fieldValue:"code";
        _fields.push(_textField);
        _fields.push(_valueField);
        
        if(this.otherFields!=undefined){
           _fields =  _fields.concat(this.otherFields);
        }

        this.fieldText  = _textField;
        this.fieldValue = _valueField;

        this.root =(this.root==undefined)?"dataset.simplecombobox":this.root;

        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config = {
            readOnly:false,
            //minChars:2,
            //store: store,
            displayField:_textField,
            name:_textField,
            valueField:_valueField,
            forceSelection : true,
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            emptyText:'未选择...',
            loadingText : '读取...',
            selectOnFocus:true,
            //value:'',
            //lazyInit : false,
            width:this.boxWidth,
            renderTo: box    
        };  
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var store = null;
                
        if(typeof this.url=='string' && this.url!=""){
            store = new Ext.data.Store({
    	        proxy : new Ext.data.HttpProxy({url: this.url,method:"POST"}),
    	        reader: new Ext.data.JsonReader({root: this.root}, _fields)
            });

            var _mode = this.mode;
            if(_mode!='remote') {
                if(this.url.indexOf('?')!=-1||this.url.indexOf('txt')!=-1){
                    store.load();
                    if(this.autoSelectFirst===true){
                        store.on('datachanged',this.selectFirst,this);
                    }
                    if(this.autoSelectRecord!=undefined){
                        store.on('datachanged',this.selectAppointedRecord,this);
                    }
                }
            }
        }else {
            if(this.dataArray==undefined) {
                this.dataArray=[];
                _config.disabled = true;
            }
            store = new Ext.data.SimpleStore({fields:(this.fields)?this.fields:[],data : (this.dataArray)?this.dataArray:[]});
        }
        _config.store = store;

        //-------------------------------------------------------------------------------
        if(this.allowBlank!=undefined) _config.allowBlank = this.allowBlank;
        if(this.listWidth!=undefined)  _config.listWidth  = this.listWidth;

        _config.readOnly = this.readOnly;
        _config.mode     = this.mode;
        
        this.el = new Ext.form.ComboBox(_config);        

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.repeatedSelect=(this.repeatedSelect==undefined)?false:this.repeatedSelect;

        if(this.repeatedSelect===false){
            var theObj = this;
            this.el.addListener("beforeselect",function(c,r,index){
                //debugger;
                if(c.getValue()==r.get(theObj.fieldValue)){
                    c.collapse();
                    return false;
                }
            });
        }

        if(this.page.isView()){         //20090730 add by yujunjie
            this.el.on('beforeclick',function(){return false;});
        }
    }
});
Sail.widget.ext.comboBox = Sail.widget.ext.combox;


Sail.widget.ext.calendar = Sail.extend(Sail.widget.boxComponent,{
    enableBindData : true,

    getValue : function(){
        var _format = 'Ymd';
        if(arguments.length==1){
            _format =(arguments[0]=='yyyy-mm-dd')?'Y-m-d':_format;
        }
        
        var getDate = this.el.getValue();
        return (getDate=="")?"":getDate.format(_format);
    },
    getYear : function(){
        var s = this.getValue();
        return (s=="")?s:s.substr(0,4);
    },
    getMonth : function(){
        var s = this.getValue();
        return (s=="")?s:s.substr(4,2);
    },
    getDay : function(){
        var s = this.getValue();
        return (s=="")?s:s.substr(6,2);
    },
    
    setValue : function(v){
        if(v.indexOf('-')!=-1) v = v.replaceAll('-','');
        var v = v.substr(0,8);
        var newDate = v.substr(0,4)+"-"+v.substr(4,2)+"-"+v.substr(6,2);
        this.el.setValue((v.length!=8)?"":newDate);
    },
    
    createWidgetElement:function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config ={width:this.boxWidth,renderTo:box,format:"Y-m-d"};
        
        this.readOnly    = (this.readOnly==undefined)?false:this.readOnly;
        //_config.readOnly = this.readOnly;     //20090722170500 by yjj 限制日期输入，只能点击选择
        _config.readOnly = true;                //20090722170500 by yjj 限制日期输入，只能点击选择

        if(this.allowBlank !=undefined)  _config.allowBlank = this.allowBlank;
    
        this.el = new Ext.form.DateField(_config);        
        //this.el.setValue("");
        //this.el.focus();
        
        //if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
        if(this.page.isView()){         //20090730 add by yujunjie
            this.el.on('beforeclick',function(){return false;});
        }
        
    }
    
});
Sail.widget.ext.sDate = Sail.widget.ext.calendar;

Sail.widget.ext.timeChoice = Sail.extend(Sail.widget.boxComponent,{
    enableBindData      : true,
    createWidgetElement : function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config = {
            readOnly  : true,
            blankText : "未选择...",
            width     : this.boxWidth,
            renderTo  : box   
        };

        if(this.allowBlank!=undefined) _config.allowBlank  = this.allowBlank;

        this.el = new Ext.form.timeSelectField(_config);        
        
        if(this.disabled) this.el.disable();

        this.el.focus();
    
    }
});


Sail.widget.ext.choice = Sail.extend(Sail.widget.boxComponent,{
    enableBindData  : true,

    defaultGetValue : "idField",
    defaultSetValue : 'idField',
    
    idField     : "id",
    textField   : "text",
    valueField  : "value",
    
    mode       : 'openUrl',         //or openFn


    getIntendingHeight:function(){          //获取表格预计高度
        
        if(this.useTextArea===true){
            if(this.textAreaHeight!=undefined){
                return this.textAreaHeight;
            }else{
                return this.defaultHeight;
            }
        }else{
            return this.defaultHeight;
        }
    },
    
    getValue : function(){
        var a = arguments;
        var o = this.el.getDataObj();
        
        if(a.length==0){ 
            return o[this[this.defaultGetValue]]||'';
        }else if(a.length==1){
            if(typeof a[0]=='string'){
                return o[a[0]]||'';
            }else{
                return o[this[this.defaultGetValue]]||'';
            }
        }else{
            return o[this[this.defaultGetValue]]||'';
        }
    },
    getText : function(){
        return this.getValue(this.textField);
    },
    getData : function(){
        return this.el.getDataObj() ||{};
    },
    setURL  : function(url){
        this.el.openUrl = url;
    },
    setData : function(){
        var a = arguments;
        
        if(a.length==1){
            if(typeof a[0] =='object'){
                this.el.setDataObj(a[0]);
                this.el.setValue(a[0][this.textField]);        
                return;
            }
        }else if(a.length==2){
            if(typeof a[0]=='string' && typeof a[1]=='string'){
                var o = {};
                o[this.idField] = a[0];
                o[this.textField]  = a[1];
                
                this.el.setDataObj(o);
                this.el.setValue(o[this.textField]);    
                return;    
            }
        }else if(a.length==3){
            if(typeof a[0]=='string' && typeof a[1]=='string' && typeof a[2]=='string'){
                var o = {};
                o[this.idField] = a[0];
                o[this.textField]  = a[1];
                o[this.valueField]  = a[2];
                
                this.el.setDataObj(o);
                this.el.setValue(o[this.textField]);      
                return;  
            }
        }
        
        alert("组件 name="+this.name+"，title="+this.title+"，调用setData时，传入参数格式不正确！");
        
    },
    
    setValue : function(v){
        //debugger;
        var o = {};
        o[this.textField] = v;
        this.el.setDataObj(o);
        
        this.el.setValue(v);
    },

    bindData : function(bd){
        //debugger;
        if(bd==undefined) 
        bd = this.getBusiness();
        
        if(this.dataIndex!=undefined && this.nameIndex!=undefined){
            var v = Sail.getSubObj(bd,this.dataIndex)||"";
            var t = Sail.getSubObj(bd,this.nameIndex)||"";
            var i = "";
            
            //if(this.idIndex!=undefined)
            //    i = Sail.getSubObj(bd,this.nameIndex)||"";
            
            this.setData(v,t,i);
        }else{
            alert("组件="+this.name+",类别="+this.type+",在执行数据绑定时，没有找到dataIndex定义！");
        }
    },
    
    clear : function(){
        this.el.setValue("");
        this.el.openFn  ="";
        this.el.openUrl ="";
    },
    
    change : function(){
        var a = arguments;
        this.enable();
        var newConfig = {};

        if(a.length==1){
            if((typeof a[0] ) =="object"){
                Sail.apply(newConfig,a[0]);
            }else{
                newConfig[this.mode]=config;
            }
        }
        
        this.setValue('');
        Sail.apply(this.el,newConfig);
        Sail.apply(this,newConfig);
        
    },
    
    createWidgetElement : function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        //debugger;
        var _config = {
            readOnly  : true,
            blankText : "未选择...",
            width     : this.boxWidth,
            openUrl   : this.openUrl,
            openFn    : this.openFn,
            showValue : (this.text)?this.text:"text",
            dataValue : (this.value)?this.value:"id",
            renderTo  : box   
        };

        if(this.allowBlank!=undefined) _config.allowBlank  = this.allowBlank;
        if(this.openWidth!=undefined)  _config.openWidth  = this.openWidth;
        if(this.openHeight!=undefined) _config.openHeight  = this.openHeight;
        if(this.commonParameter!=undefined) _config.commonParameter = this.commonParameter;

        if(this.useTextArea === true)   _config.useTextArea = this.useTextArea;
        if(this.textAreaHeight !=undefined)   _config.textAreaHeight = this.textAreaHeight;
    
        this.el = new Ext.form.SelectField(_config);        
        
        if(this.disabled) this.el.disable();

        //this.el.focus();
        if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
        
        if(this.page.isView()){         //20090730 add by yujunjie
            this.el.on('beforeclick',function(){return false;});
        }
        
    }
    
});

Sail.widget.ext.treeChoice = Sail.extend(Sail.widget.ext.choice,{
    fnTemplet : "Sail.showtree({0})",
    //openFn : "Sail.showtree({0})",
    openUrl : "",
    openFn  : "",

    getIntendingHeight:function(){          //获取表格预计高度
        
        if(this.useTextArea===true){
            if(this.textAreaHeight!=undefined){
                return this.textAreaHeight;
            }else{
                return this.defaultHeight;
            }
        }else{
            return this.defaultHeight;
        }
    },
        
    reSetOpenFn : function(){
        if(this.openFn=="" && this.openUrl=="") return;
        
        var tmpConfig  = {};
        Sail.apply(tmpConfig,this.treeConfig);
        tmpConfig.selectedNodes = this.getValue();
        
        var str = tmpConfig.toJSONString();
        this.openFn = this.fnTemplet.replace("{0}",str);
        this.el.openFn = this.openFn;
    },
    
    change : function(config){
        this.clear();

        if(typeof config =='object'){
            this.treeConfig = {};
    
            Sail.apply(this.treeConfig,config);
            var str = this.treeConfig.toJSONString();
            this.openFn = this.fnTemplet.replace("{0}",str);
            this.el.openFn = this.openFn;
        }
    },
    
    createWidgetElement : function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        if(this.treeConfig!=undefined){
            var str = this.treeConfig.toJSONString();
            this.openFn = this.fnTemplet.replace("{0}",str);
        }
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config = {
            readOnly  : true,
            blankText : "未选择...",
            width     : this.boxWidth,
            openUrl   : this.openUrl,
            openFn    : this.openFn,
            showValue : (this.text)?this.text:"text",
            dataValue : (this.value)?this.value:"id",
            renderTo  : box   
        };

        if(this.allowBlank!=undefined) _config.allowBlank  = this.allowBlank;
        if(this.openWidth!=undefined)  _config.openWidth  = this.openWidth;
        if(this.openHeight!=undefined) _config.openHeight  = this.openHeight;
        if(this.commonParameter!=undefined) _config.commonParameter = this.commonParameter;
        if(this.useTextArea === true)   _config.useTextArea = this.useTextArea;
        if(this.textAreaHeight !=undefined)   _config.textAreaHeight = this.textAreaHeight;

        this.el = new Ext.form.SelectField(_config);        
        
        if(this.disabled) this.el.disable();

        //this.el.focus();
        if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
        
        this.el.on('afterclick',function(){
            this.reSetOpenFn();
        },this);
    }
});

Sail.widget.ext.selectField = Sail.widget.ext.choice;


//=======================================================================================
//=======================================================================================
Sail.widget.regularBoxComponent = Sail.extend(Sail.widget.boxComponent,{

    createTitleEl : function(){
        var ocd = this.getOCD();
        
        //-------------------------------------------------------------------------------
        //构造标题
        //-------------------------------------------------------------------------------
        var firstFlag = false;
        if(this.titleDiv==undefined){
            var c = {
                parent: ocd,
                style : {
                    left: 0,top: 0,
                    height:22,width:100,
                    paddingTop:4,textAlign:'center',
                    backgroundColor:'#e6e6e6',
                    border:'1px #cccccc solid',cursor:"default"
                }
            };
            c.style.color = (this.textColor==undefined)?"#000000":this.textColor;
            this.titleDiv = new Sail.DIV(c);
            firstFlag = true;
        }else{
            var _style={width:0};
            if(this.textOverflow){ 
                _style.cursor = 'default';
                _style.textOverflow ='clip'; 
                this.textOverflow = false; 
            }
            this.titleDiv.applyStyle(_style);
        }

        var mustTitle = this.mustMark+this.title;
        //var mustTitle = "<font color='#ff0000'>"+this.title+"</font>";
        
        var _title = (this.allowBlank===false && this.isUnited!==true)?mustTitle:this.title;
        Sail.apply(this.titleDiv.el,{innerHTML:_title,align:"left",noWrap:true});
        
        var actWidth = (firstFlag)?this.titleDiv.getOffset().width:this.titleDiv.getScroll().width;

        //-------------------------------------------------------------------------------
        //如果标题宽度大于标题可用宽度，则折叠标题
        //-------------------------------------------------------------------------------
        var titleMaxWidth = this.width-this.colonWidth-this.inputMinWidth;
        titleMaxWidth=(titleMaxWidth<=0)?this.titleMinWidth:titleMaxWidth;
        
        if(actWidth>titleMaxWidth){
            var tw = this.enableUseScale();
            this.titleDiv.applyStyle({cursor:'help',overflow:"hidden", textOverflow:"ellipsis",  width:(tw==0)?titleMaxWidth:tw});
            this.titleDiv.setHTML("<noBR>"+_title+"</noBR>");
            this.textOverflow = true;
            
            if(this.tip==undefined){
                this.tip = new Ext.ToolTip({
                    target: this.titleDiv.el,width:actWidth,html: _title,trackMouse:true
                });
            }else{
                this.tip.width = actWidth;
                this.tip.html = _title;
            }
        }
        else{
            if(!firstFlag){
                if(this.tip!=undefined){
                    this.tip.destroy();
                    this.tip=null;
                }
            }
            this.titleDiv.setWidth(actWidth);
        }
            
        this.titleWidth = parseInt(this.titleDiv.getWidth().replace('px',''),10);
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.haveColon===true){
            this.crateColon(this.titleWidth);
        }
    },

    createElBox : function(){
        //debugger;
        var begin = (this.titleWidth==undefined)?0:this.titleWidth+4;
        
        this.boxWidth = this.width - begin-120;
        
        var ocd = this.getOCD();
        this.boxDiv = new Sail.DIV({
            parent: ocd,
            style : {
                left: begin,top: 0,width:this.boxWidth,height:22,
                border:'0px #ff0000 solid',cursor:"default"}
        });
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var begin2 = begin+this.boxWidth;
        this.sLabelDiv = new Sail.DIV({
            parent: ocd,
            style : {
                left: begin2,top: 0,width:120,height:22,
                paddingTop:4,paddingLeft:2,
                border:'0px #ff0000 solid',cursor:"default"}
        });
        
        if(this.sLabel!=undefined){
            this.sLabelDiv.setHTML(this.sLabel);
        }
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        return this.boxDiv.el;
    },

    createElStructure : function(){
        //debugger;
        if(this.showTitle===true)
            this.createTitleEl();                       //创建标题 el
            
        var el = this.createElBox();
        
        return el;
    }
});

Sail.widget.ext.regularInput = Sail.extend(Sail.widget.regularBoxComponent,{
    enableBindData      : true,
    haveColon           : false,

    haveDynamicSLabel   : function(){
        if(this.sLabelValues!=undefined && (typeof this.sLabelValues=='string')){
            return true;
        }
        return false;
    },
    updateDynamicSLable : function(index,value){
        this.sLabel = this.sLabel.replace("{"+index+"}",value);
        this.sLabelDiv.setHTML(this.sLabel);
        //debugger;
    },
    bindData : function(bd){
        
        if(this.dataIndex!=undefined){
            var v = Sail.getSubObj(bd,this.dataIndex);
            this.setValue(v);
            
            if(this.haveDynamicSLabel()){
                var fields = this.sLabelValues.split(",");
                for(var i=0;i<fields.length;i++){
                    var v = Sail.getSubObj(bd,fields[i]);
                    if(v==undefined)v=0;
                    this.updateDynamicSLable(i,v);
                }
            }
        }else{
            //alert("组件="+this.name+",类别="+this.type+",在执行数据绑定时，没有找到dataIndex定义！");
        }
    },
    
    createWidgetElement : function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        var _config ={width:this.boxWidth,renderTo:box};

        if(this.readOnly!=undefined)    _config.readOnly    = this.readOnly;
        if(this.minLength!=undefined)   _config.minLength   = this.minLength;
        if(this.maxLength!=undefined)   _config.maxLength   = this.maxLength;
        if(this.allowBlank!=undefined)  _config.allowBlank  = this.allowBlank;

        this.el = new Ext.form.TextField(_config);        
        //this.el.focus();
        if(this.maxLength) this.el.el.dom.maxLength = this.maxLength;
    }
});

//=======================================================================================
//=======================================================================================

Sail.widget.ext.unitedItem = Sail.extend(Sail.widget.boxComponent,{
    
    setWidth : function(w){
        //debugger;  
        this.width = w;
        this.container.setWidth(w-4);
        this.refresh();    
        
        this.layout.reLayout({width:this.boxWidth-4}); 
        //this.getOCD().style.border = "1px #00ff00 solid";
        this.adjustByButton();       
    },
    disable : function(){
        Sail.widget.ext.unitedItem.superclass.disable.call(this);
        for(var i=0;i<this.united.items.length;i++){
            var w = this.ownerFrame.getItem(this.united.items[i]['name']);
            w.disable();
        }
    },
    enable : function(){
        Sail.widget.ext.unitedItem.superclass.enable.call(this);
        for(var i=0;i<this.united.items.length;i++){
            var w = this.ownerFrame.getItem(this.united.items[i]['name']);
            w.enable();
        }
    },
    getItem : function(name){
        for(var i=0;i<this.united.items.length;i++){
            if(this.united.items[i]['name']==name)
                return this.ownerFrame.getItem(name);
        }
        return null;
    },
    repairItems : function(){
        for(var i=0;i<this.united.items.length;i++){
            var item = this.united.items[i];
            
            if(this.allowBlank===false){ item['allowBlank']=false;   }
            if(item["name"]==undefined){ item["name"]=item["title"]; }
            if(i==0){ 
                if(item.showTitle==undefined) item.showTitle = false;
            }else{     
                if(item.haveColon==undefined) item.haveColon = false;
                item.isUnited  = true;
            }
        }
    },
    createLayouSet : function(){
        var _layout = [{items:[]}];
        
        for(var i=0;i<this.united.items.length;i++){
            _layout[0]['items'].push({name:this.united.items[i].name});
        }
        return _layout;
    },
    createLayoutConfig : function(){
        var _layoutConfig = {columns:this.united.items.length};
        if(this.united.width!=undefined && (this.united.width instanceof Array)){
            _layoutConfig.width = this.united.width;
        }
        
        return _layoutConfig;
    },
    haveButton : function(){
        var rbt=[];
        
        for(var i=0;i<this.united.items.length;i++){
            if(this.united.items[i]['type']=='button') 
                rbt.push(this.united.items[i]);
        }
        return rbt;
    },
    adjustByButton : function(){
        var rbt = this.haveButton();
        if(rbt.length>0){
            //debugger;
            var widths = [];
            var totalWidth = this.boxWidth;
            var compWidth  = 0;
            var perWidth   = totalWidth/this.united.items.length;
            
            for(var i=0;i<rbt.length;i++){
                var w = this.ownerFrame.getItem(rbt[i].name);
                compWidth+=(perWidth-w.getWidth());
            }
            
            var perCompWidth = compWidth/(this.united.items.length-rbt.length);
            
            for(var i=0;i<this.united.items.length;i++){
                var item = this.united.items[i];
                var w = this.ownerFrame.getItem(item.name);
                var adjustWidth = (w.type!='button')?perCompWidth:0;
                adjustWidth = (this.haveAdjust===true)?0:adjustWidth;
                var _width = w.getWidth()+adjustWidth;
                widths.push(_width/totalWidth);
            }
            
            this.haveAdjust = true;
            var lc = this.createLayoutConfig();
            lc.width = [].concat(widths);
            this.layout.reLayout({layoutConfig:lc});
        }
    },
    
    createWidgetElement:function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        
        //-------------------------------------------------------------------------------
        //组件配置对象的构造
        //-------------------------------------------------------------------------------
        this.repairItems();        

        this.layout = new Sail.layoutConstructor({
            items        : this.united.items,
            layoutConfig : this.createLayoutConfig(),
            layout       : this.createLayouSet(),
            parentDiv    : box,
            ownerFrame   : this.ownerFrame,
            ownerGroup   : this.ownerFrame.getChildren(),
            page         : this.ownerFrame.getBelongedPage(),
            widgetPrefix : this.ownerFrame.widgetPrefix,
            width        : this.boxWidth,
            height       : this.height,
            constructTo  : this,
            padding      : {left:0,right:0,top:0,bottom:0},
            space        : {row:10,col:4}            
        });
        
        
        this.layout.doLayout();
        this.adjustByButton();
        
        this.el = {};
    }
});    


Sail.widget.ext.dateCoverage = Sail.extend(Sail.widget.ext.unitedItem,{

    itemNames : ['beginDate','endDate'],
    splitText : "至",
    dataIndex : ["begindate","enddate"],

    initComponent : function(){
        var itemDefine = [{   
            type : "calendar",   
            name : this.itemNames[0]||'beginDate'
        },{   
            type : "calendar",      
            name : this.itemNames[1]||'endDate',
            title: this.splitText
        }];
        
        if(this.dataIndex !=undefined && (this.dataIndex instanceof Array)){
            itemDefine[0].dataIndex = this.dataIndex[0];
            itemDefine[1].dataIndex = this.dataIndex[1];
        }

        this.united = {items:itemDefine};
    },
    
    getValue : function(){
        var o = {};
        o[this.dataIndex[0]]=$(this.itemNames[0]).getValue();
        o[this.dataIndex[1]]=$(this.itemNames[1]).getValue();
        return o;
    },
    
    setValue : function(o){
        $(this.itemNames[0]).setValue(o[this.dataIndex[0]]||"");
        $(this.itemNames[1]).setValue(o[this.dataIndex[1]]||"");
    },
    
    bindData : function(db){
        if(bd==undefined) 
        bd = this.getBusiness();
        
        if(this.dataIndex!=undefined){
            if(this.dataIndex instanceof Array){
                var v = Sail.getSubObj(bd,this.dataIndex[0]);
                $(this.itemNames[0]).setValue(v);

                var v = Sail.getSubObj(bd,this.dataIndex[1]);
                $(this.itemNames[1]).setValue(v);
            }
        }
    },
    
    afterCreateWidget : function(){
        //debugger;
        var beginItem = $('beginDate');
        var endItem   = $('endDate');
        
        beginItem.on('aftersetvalue',function(dateField,oldDate,newDate){
            var endDate = endItem.getValue();                    //取得当前结束日期
            
            if(newDate>endDate && endDate!=''){                  //判断
                Sail.showMsg('开始日期不能大于结束日期！');      //显示提示信息
                dateField.setValue(Sail.formatDate(oldDate),''); //恢复 开始日期 修改前的值
            }
        });

        endItem.on('aftersetvalue',function(dateField,oldDate,newDate){
            var beginDate = beginItem.getValue();            //取得当前开始日期 
            
            if(newDate<beginDate){                               //判断
                Sail.showMsg('结束日期不能小于结束日期！');      //显示提示信息
                dateField.setValue(Sail.formatDate(oldDate),''); //恢复 结束日期 修改前的值
            }
        });
        
    }

});

Sail.widget.ext.buttonBar = Sail.extend(Sail.widget.boxComponent,{
    showTitle : false,
    haveColon : false,
    align     : 'left',

    btName : [],
    btEl   : [],
    icons  : [],
    defaultIcon : "mybutton", 
    
    setWidth : function(w){        
        //debugger;
        this.width = w;
        this.container.setWidth(w);
        
        this.btbar.setWidth(w);
    },
    
    getButton : function(name){
        for(var i=0;i<this.btName.length;i++){
            if(this.btName[i]==name)
                return this.btEl[i];
        }
        return null;
    },
    getButtonIndex : function(){
        for(var i=0;i<this.btName.length;i++){
            if(this.btName[i]==name)
                return i;
        }
        return -1;
    },
    addButton : function(name,icon){
        var haveflag = false;
        for(var i=0;i<this.btName.length;i++){
            if(this.btName[i]==name)
                haveflag=true;
        }
        if(!haveflag) {
            this.btName.push(name);
            this.icons.push(icon);
        }
    },
    addButtonHandler : function(btname,handler){
        this.addHandler(btname,handler);
    },
    addHandler: function(name,handler){
        var bt = this.getButton(name);
        if(bt!=null) {
            bt.on('click',handler);
        }else{
            alert('没有找到按钮：'+name);
        }
    },

    formatButtons : function(){
        if(this.items==undefined) return;
        
        var nb = [];
        for(var i=0;i<this.items.length;i++){
            var o = {name:'',icon:this.defaultIcon};
            if(typeof this.items[i]=='object'){
                Sail.apply(o,this.items[i]);
            }else{
                o.name=this.items[i];
            }
            nb.push(o);
        }
        this.items = [].concat(nb);
    },
    addButton : function(name,icon){
        var haveflag = false;
        for(var i=0;i<this.btName.length;i++){
            if(this.btName[i]==name)
                haveflag=true;
        }
        if(!haveflag) {
            this.btName.push(name);
            this.icons.push(icon);
        }
    },
    
    hideButton : function(name){
        name = (name instanceof Array)?name:[name];
        for(var i=0;i<name.length;i++){
            var bt = this.getButton(name[i]);
            bt.hide();
        }
    },
    showButton : function(name){
        name = (name instanceof Array)?name:[name];
        for(var i=0;i<name.length;i++){
            var bt = this.getButton(name[i]);
            bt.show();
        }
    },
    createBtBar : function(){

        if(this.items!=undefined){
            this.formatButtons();

            for(var i=0;i<this.items.length;i++)
                this.addButton(this.items[i].name,this.items[i].icon);
        }

        this.btbar = new Sail.DIV({
            parent: this.getOCD(),
            style : {left: 0,top: 0,width:this.width,border:((this.border===false)?'0px #8DB2E3 solid':'1px #8DB2E3 solid')}
        });

        var _html = ["<table width='100%' border=0 cellpading=0 cellspacing=2><tr height=21>"];
        if(this.align=='right') _html.push("<td width=100%></td>");
        
        for(var i=0;i<this.items.length;i++){
            _html.push("<td align=left><div id='"+this.btbar.getID()+"_"+i+"'></div></td>");
        }
        if(this.align=='left') _html.push("<td width=100%></td>");

        _html.push("</tr></table>");
        this.btbar.el.innerHTML = _html.join("");
        
        for(var i=0;i<this.items.length;i++){
            this.btEl.push(new Ext.Button({
                text:"　"+this.btName[i],
                iconCls:'x-btn-left '+this.icons[i],
                cls: 'x-btn-text-icon',
                renderTo:this.btbar.getID()+"_"+i
            }));
        }
    
    },
    createWidgetElement:function(){

        var box = this.createElStructure();         //搭建输入类组件的展现结构
        //var ocd = this.getOCD();
        //ocd.style.border = '1px #8DB2E3 solid';
        this.createBtBar();
    }    
});

//=======================================================================================
//=======================================================================================
Sail.widget.ext.label = Sail.extend(Sail.widget.boxComponent,{
    border  : false,
    icon    : false,
    //bold    : false,

    showTitle   : false,
    textColor   : "#FA6003",
    autoEllipsis: true,
    ellipsised  : false,
    
    paddingLeft : 4,
    paddingTop  : 2,

    defaultHeight : 18,
    
    initComponent : function(){
        this.showTitle = false;
        //this.defaultHeight = 22;
    },
    
    setChangedCls : function(){
        //debugger;
        if(this.boxDiv!=undefined){
            this.boxDiv.addClass('icon-datachanged');
        }
    },

    on : function(eventName, handler, scope, options){
        Ext.get(this.el.el).on(eventName, handler, scope, options);
    },
    
    change : function(config){
        if(typeof config =='string'){
            config = {title:config};
            Sail.apply(this,config);
            this.createEl();
        }else if(typeof config =='object'){
            Sail.apply(this,config);
            this.createEl();
        }else{
            if(config==undefined){
                var config = {title:""};
                Sail.apply(this,config);
                this.createEl();
            }else{
                Sail.showMsg('文本标签参数错误！');
            }
        }
    },
        
    createEl:function(){
        //debugger;
        
        var w = Sail.getLabelWidth(this.title);
        if(this.autoEllipsis===true){
            this.ellipsised = (w>this.width)?true:false;
        }

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var defaultStyle = {
            left: 0,top : 0,width:this.width,height:this.height,
            paddingLeft : this.paddingLeft, 
            paddingTop  : this.paddingTop,
            textAlign   : (this.align==undefined)?'left':this.align,

            color   : this.textColor,
            //font    : ((this.bold===true)?"bold":"")+" 12px tahoma,arial,verdana,sans-serif",
            cursor  : this.ellipsised?"help":"default"
        };
        
        if(this.border!=undefined){
            if(this.border===true) 
                defaultStyle.border="1px #c0c0c0 solid";
            else if(this.border===false){
                defaultStyle.border="0px #c0c0c0 solid";
            }else{
                defaultStyle.border = this.border;
            }
        }
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.icon===true){
            defaultStyle.paddingLeft = this.paddingLeft+16;
            defaultStyle.backgroundRepeat="no-repeat";
            this.iconCls= (this.iconCls==undefined)?"label_default":this.iconCls;
        }
        
        defaultStyle.overflow="hidden";
        if(this.ellipsised){
            defaultStyle.textOverflow="ellipsis";
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.style!=undefined) Sail.apply(defaultStyle,this.style);
        if(this.boxDiv==undefined){
            this.boxDiv = new Sail.DIV({parent: this.getOCD(),style : defaultStyle});
        }else{
            this.boxDiv.applyStyle(defaultStyle);
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.title!=undefined){
            //debugger;
            this.boxDiv.setHTML(this.ellipsised?"<noBR>"+this.title+"</noBR>":this.title);
        }
        
        this.boxDiv.addClass(this.iconCls);
        
        this.el = this.boxDiv;
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.ellipsised){
            var _title = this.title;

            if(this.tip==undefined){
                this.tip = new Ext.ToolTip({
                    target: this.boxDiv.el,width:w/2,html: _title,trackMouse:true
                });
            }else{
                this.tip.width = w/2;
                this.tip.html = _title;
            }
        }else{
            if(this.tip!=undefined){
                this.tip.destroy();
                this.tip = null;
            }
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.html!=undefined){
            this.boxDiv.setHTML(this.html);
        }
    },
    
    createWidgetElement:function(){
        this.createEl();
    },
    afterCreateWidget :function(){
        //必须此空方法，以覆盖基类的此方法
    }
});


//=======================================================================================
//=======================================================================================
Sail.widget.ext.iframe = Sail.extend(Sail.widget.boxComponent,{
    border : false,
    alwaysBorder : false,
    
    setHeight : function(h){
        this.height = h;
        this.container.setHeight(h);
        this.elDiv.setHeight(h);
    },
    setWidth : function(w){        
        this.width = w;
        this.container.setWidth(w);
        
        this.elDiv.setWidth(w);
    },    
    setSrc : function(src){
        //this.elDiv.el.children[0].src = "#";
        
        if(src!=undefined && src!=""){
            if(this.alwaysBorder==false){
                this.elDiv.el.style.border = '0px #8DB2E3 solid';
            }
            this.elDiv.el.children[0].src = src;
        }
    },
    
    creatEl : function(){
        var _src = (this.src!=undefined && this.src!='')?this.src:"#";
    
        _border = (_src=='#')?'1px #8DB2E3 solid':_border;
        var _border = ((this.border===false)?'0px #8DB2E3 solid':'1px #8DB2E3 solid');
                
        this.elDiv = new Sail.DIV({
            parent: this.getOCD(),
            style : {left: 0,top: 0,width:this.width,border:_border}
        });

        _html = "<iframe src="+_src+" frameborder=0 style=\"position: absolute; width: '100%'; height: '100%'; \"></iframe>";
        this.elDiv.el.innerHTML = _html;
    },
    
    createWidgetElement:function(){
        this.creatEl();
    }    
});

//=======================================================================================
//=======================================================================================
Sail.widget.ext.customWidget = Sail.extend(Sail.widget,{
    defaultHeight : 40,
    
    setHeight : function(h){
    },
    setWidth : function(w){
    },
    
    createWidgetElement:function(){
        this.el  = document.createElement( "DIV" );  
                    
        //this.el.style.width=200;
        //this.el.style.height=50; 
        //this.el.style.border = "1px #ababab solid";        
        debugger;
        this.el.className = "test_yjj";
        this.getOCD().appendChild(this.el);
        //this.el = new Sail.DIV({parent: this.getOCD(),style : defaultStyle});
    },
    afterCreateWidget : function(){
    }
});﻿//=======================================================================================
//类名 ： Sail.widget.ext.form
//说明 ： 表单容器对象
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================
Sail.widget.ext.form = Sail.extend(Sail.widget,{
    showTitle : true,
    border    : true,
    
    defaultIconCls : 'fc-bb-default-out',
    defaultHeight  : 100,
    
    collapsed : false,
    
    alwaysShow : ",打印,关闭,",
    
    //===================================================================================
    //方法 ： some func for init before create element
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    initComponent : function(){
        
        Sail.widget.ext.form.superclass.initComponent.call(this);

        this.addEvents('titleClick');
        
        this.items = this.items || [];
        for(var i=0;i<this.items.length;i++){
            var item = this.items[i];
            item.name = item.name || item.title;
        }
        
        this.title  = this.title || "信息";
        
        this.repairButtons();

    },
    
    repairButtons : function(){
        this.buttons = this.buttons ||[];
        this.buttons = (this.buttons instanceof Array)?this.buttons:[this.buttons];
        
        var nb = [];
        for(var i=0;i<this.buttons.length;i++){
            var o = {icon:this.defaultIconCls,hidden:false};
            if(typeof this.buttons[i]=='object'){
                Sail.apply(o,this.buttons[i]);
                if(o.name==undefined && o.text!=undefined && o.text!=""){
                    o.name = o.text;
                }                
                if(o.text==undefined && o.name!=undefined && o.name!=""){
                    o.text = o.name;
                }                
            }else{
                o.name=this.buttons[i];
                o.text=this.buttons[i];
            }
            if(o.text.indexOf('保存')!=-1) o.icon = "fc-bb-save-out";
            if(o.text=='打印') o.icon = "fc-bb-print-out";
            if(o.text=='关闭') o.icon = "fc-bb-close-out";
            if(o.text=='导出') o.icon = "fc-bb-output-out";
            nb.push(o);
        }
        this.buttons = [].concat(nb);

        if(this.isSearch === true){
            this.addButton('查询','fc-bb-search-out');
            this.addButton('重置','fc-bb-reset-out');
        }
        
        if(this.page.isView()){
            for(var i=0;i<this.buttons.length;i++){
                if(this.alwaysShow.indexOf(","+this.buttons[i].text+",")==-1){
                    this.buttons[i].hidden = true;
                }
            }
        }
    },

    addButton : function(text,icon){
        var haveflag = false;
                
        for(var i=0;i<this.buttons.length;i++){
            if(this.buttons[i].text==text)
                haveflag=true;
        }
        if(!haveflag) {
            this.buttons.push({text:text,name:text,icon:icon,hidden:false});
        }
    },
    
    //===================================================================================
    //方法 ： some func for change size 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setHeight : function(h){
        this.height = h;
        this.container.setHeight(h);

        var bodyHeight = this.getBodyHeight();
        this.body.setHeight(bodyHeight);

        var childer = this.children[0];
        childer.setHeight(bodyHeight-2);
        
        if(this.tabLayouts)
            this.tabLayouts.reLayout({height:bodyHeight-2});
    },
 
    setWidth : function(w){
        this.width = w;
        this.container.setWidth(w);

        this.body.setWidth(this.width);
        if(this.div_splitBar)
            this.div_splitBar.setWidth(this.width);
            
        this.reCreateTitleBar();

        var childer = this.children[0];
        childer.setWidth(this.width);
        
        if(this.tabLayouts)
            this.tabLayouts.reLayout({width:this.width});
    },
    
    setSize : function(w,h){
        this.width  = w;
        this.height = h;
        this.container.setWidth(w);
        this.container.setHeight(h);

        var bodyHeight = this.getBodyHeight();
        this.body.setHeight(bodyHeight);

        this.body.setWidth(this.width);
        if(this.div_splitBar)
            this.div_splitBar.setWidth(this.width);
            
        this.reCreateTitleBar();

        var childer = this.children[0];
        childer.setWidth(this.width);
        childer.setHeight(bodyHeight-2);
        
        if(this.tabLayouts)
            this.tabLayouts.reLayout({width:this.width,height:bodyHeight-2});
        
    },
    
    getIntendingHeight : function(){
        if(Sail.isObjArray(this.layout)){
            var _layout = Sail.copyObjArray2(this.layout);
        }else{
            if(this.layout!=undefined)
                var _layout = Sail.copyObjArray3(this.layout);
            else{ 
                var _layout = [];
                this.items = this.items ||[];
                for(var i=0;i<this.items.length;i++){
                    _layout.push({
                        items :[ { name:((this.items[i].name==undefined)?this.items[i].title:this.items[i].name)}]
                    });
                }
            }
        }
        
        if(this.layoutConfig==undefined){
            this.layoutConfig = {columns : 1};        
        }
        
        var _items  = Sail.copyObjArray(this.items);
        
        var tmplayout = new Sail.layoutConstructor({
            executor     : this.name,
            items        : _items,
            layoutConfig : this.layoutConfig,
            layout       : _layout,
            widgetPrefix : this.widgetPrefix,            
            isSimulation : true
        });
        
        var _height = tmplayout.computeHeight();
        tmplayout = null;
        
        return _height+((this.showTitle==true)?26:0);
    },
    
    //===================================================================================
    //方法 ： some func for bt search & reset 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getSearch : function(){
        var _search = new Sail.stringBuffer();
        
        for(var i=0,len=this.items.length;i<len;i++){
            var item = this.items[i];
            
            var w = this.ownerFrame.getItem(item.name);
            if(w.type.indexOf("button")!=-1) continue;
            
            _search.push(w.getSearch());
        }
        return _search.toString(); 
    },
    reset : function(){
        for(var i=0,len=this.items.length;i<len;i++){
            var item = this.items[i];
            
            var w = this.ownerFrame.getItem(item.name);
            if(w.type.indexOf("button")!=-1) continue;
            
            w.setValue("");
        }
        return true;
    },
    
    //===================================================================================
    //方法 ： some func for reset tabs when click 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getTabHTML : function(config){
        if(this.tp_td == undefined){
            this.tp_td = new Sail.Template(
                "<td id={tdid} width={tdWidth}>",
                    "<table cellspacing=0 cellpadding=0 border=0 style='cursor:hand;table-layout:fixed'>",
                        "<tr height=23>",
                            "<td class='tc-tab-leftspac' width=2></td>",         //标签左空白间隔
                            "<td class='{leftBorder}' width=3></td>",            //左边框
                            "<td class='{commentCls}' width=6></td>",            //图标左留白
                            "<td class='{commentCls}' width=16>",                //图标
                                "<div class='{iconCls}' style='width:16;height:16'></div>",
                            "</td>",
                            "<td class='{commentCls}' width=2></td>",            //图标文本间隔
                            "<td class='{commentCls}' height=23 width={titleW} style='padding-top:5px'>{title}</td>", //标签文本
                            "<td class='{commentCls}' width=40 align=right>",
                                //"<div class='icon-tabs-close' style='width:13;'></div>",
                            "</td>",           //右留白
                            "<td class='{rightBorder}' width=3></td>",            //右边框
                        "</tr>",
                    "</table>",
                "</td>"
            );
        }
        
        return this.tp_td.apply({
            leftBorder  : "tc-tab-leftborder-active",
            rightBorder : "tc-tab-rightborder-active",
            commentCls  : "tc-tab-centen-active",
            iconCls     : "tc-tab-icon",
            tdid        : config.id,
            titleW      : config.titleWidth,
            tdWidth     : config.tdWidth,
            title       : config.title
        });
        
    },

    getTitleBarHTML : function(){               //创建一个tabs标签tab的HTML代码
        this.tp_table = new Sail.Template(
            '<table style="cursor:hand;table-layout:fixed" height=23 cellspacing=0 >',
                '<tr height=23>',
                '<td class="tc-tab-leftspac" width=2></td>',
                '{td}</tr>',
            '</table>'
        );

        var w = Sail.getLabelWidth(this.title,"bold 12px verdana");
        var td = this.getTabHTML({
            id          : this.div_title.getID()+"-0",
            titleWidth  : w,
            tdWidth     : (2+3+6+16+2+w+40+3),
            title       : this.title
        });

        var table = this.tp_table.apply({td:td});
        
        return table;
    },
    
    bindEvent2Tab  : function(){
        var tdid = this.div_title.getID()+"-0";
        //debugger;
        var td = Ext.get(tdid);
        td.on('click',this.onClick,this);
        td.on('dblclick',this.onDbClick,this);
    },
    
    onClick : function(e,target){
        if(this.collapsed===true){
            this.expand();
        }else{
            this.collapse();
        }

        this.fireEvent('titleClick',this,e);
    },

    onDbClick : function(e,target){
        if(e.ctrlKey===true){
            //debugger;
        }
    },

    getActualHeight : function(){
        return (this.collapsed==true)?26:this.height;
    },
    
    collapse : function(){
        this.collapsed=true;
        with(this.body.el){
            filters[0].Apply();
            style.visibility = (style.visibility=='hidden')?"visible":"hidden";
            filters[0].play();
        }

        (function(){
            this.ownerFrame.layoutC.reLayout();
        }).defer(450, this);;
    },    

    expand : function(){
        this.collapsed=false;
        
        with(this.body.el){
            filters[0].Apply();
            style.visibility = (style.visibility=='hidden')?"visible":"hidden";
            filters[0].play();
        }
        
        this.ownerFrame.layoutC.reLayout();
    },    
    //===================================================================================
    //方法 ： some func for bars 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    reCreateTitleBar : function(){
        var needFlag = this.reCreateButtonBar();
        
        var bbWidth  = (needFlag)?this.getBtBarWidth():0;
        var width    = this.width - ((bbWidth==0)?0:bbWidth+18);
        
        if(this.div_title)
            this.div_title.setWidth(width);        

    },
    
    createTitleBar : function(){            //创建标题栏
        
        //-------------------------------------------------------------------------------
        //如果存在定义， 创建按钮工具栏
        //-------------------------------------------------------------------------------
        var bbWidth = (this.needButtonBar())?this.createButtonBar():0;
        
        //-------------------------------------------------------------------------------
        //创建标题栏容器
        //-------------------------------------------------------------------------------
        this.titleBarHeight = (this.titleBarHeight==undefined)?23:this.titleBarHeight;
        
        var width = this.width - ((bbWidth==0)?0:bbWidth+18);
        
        this.div_title = new Sail.DIV({
            left  : 0,
            top   : 0,
            width : width,
            height: this.titleBarHeight,
            zIndex: 10,
            border: "0px #ff0000 solid",

            parent: this.getOCD()
        });
        this.div_title.addClass((bbWidth==0)?'tc-tb':'tc-tb-needMove-right');

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.div_title_son = new Sail.DIV({
            left  : 0,
            top   : 0,
            parent: this.div_title,
            //border: "1px #ff0000 solid",
            zIndex : 10
        });
    
        var html = this.getTitleBarHTML();

        this.div_title_son.setHTML(html);
        this.bindEvent2Tab();
        
        return this.titleBarHeight;
    },

    createSplitBar : function(top){         //创建一个分隔栏
        this.splitBarHeight = 4;
        this.div_splitBar = new Sail.DIV({
            width :'100%',
            left  :0,
            top   :top-1,
            parent: this.getOCD(),
            border:'#8DB2E3 1px solid',
            zIndex:9
        });
        this.div_splitBar.addClass('form_bar');        
        return this.splitBarHeight;
    },


    //===================================================================================
    //方法 ： some func for button bar 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getBtBarWidth : function(){
        var btw = 0;
        this.btPadding = 6;
        this.btSpacing = 4;
        var w = 0;
        var count = 0;
        for(var i=0;i<this.buttons.length;i++){
            if(this.buttons[i].hidden==false){
                var text = this.buttons[i].text;
                w = Sail.getLabelWidth(text,"bold 12px verdana");
                
                btw+=16+w+this.btPadding*2;
                count++;
            }
        }
        
        btw+=this.btSpacing*(count-1);
        return btw;
    },
    getBtBarLeft  : function(){
        return this.width - 4- this.getBtBarWidth();
    },
    
    needButtonBar : function(){
        return (this.buttons.length>0)?true:false;
    },   
    
    getButtonBarHTML : function(){
        this.tp_bt = new Sail.Template(
            "<div id='{id}' style='padding:1 2 1 2;border:1px #ffffff dotted;left:{left};top:0;width:{width};height:20;overflow:hidden;position:absolute;'>",
                "<table width=100% cellspacing=0 cellpadding=0 border=0 style='cursor:hand;'>",
                    "<tr height=16>",
                        "<td width=16 class='{icon}'></td>",
                        "<td class='fc-bb-text-out'>{text}</td>",
                    "</tr>",
                "</table>",
            "</div>"
        );
        
        var barID = this.buttonBar.getID();
        var bts = [];
        var left = 0;
        for(var i=0;i<this.buttons.length;i++){
            var bt = this.buttons[i];
            var width = Sail.getLabelWidth(bt.text)+26;
            var bthtml = this.tp_bt.apply({
                id   : barID+'_'+bt.name,
                left : left,
                width: (bt.hidden==false)?width:0,
                icon : bt.icon,
                text : bt.text
            });
            
            bts.push(bthtml);
            left+=(bt.hidden==false)?(width+4):0;
        }
        return bts.join("");
    }, 
    
    getButton : function(btName){
        return Ext.get(this.buttonBar.getID()+"_"+btName);
    },

    addButtonHandler : function(btname,handler,scope){
        this.getButton(btname).on('click',handler,scope);
    },

    bindEvent2Button : function(){
        var barID = this.buttonBar.getID();
        
        for(var i=0;i<this.buttons.length;i++){
            var id = barID+'_'+this.buttons[i].name;
            var bt = Ext.get(id);
            
            bt.on('mouseover',function(e,target){
                this.dom.style.border = "1px #a0a0a0 dotted";
                this.dom.style.backgroundColor = "#f0f0f0";
            },bt);

            bt.on('mouseout',function(e,target){
                this.dom.style.border = "1px #ffffff dotted";
                this.dom.style.backgroundColor = "#ffffff";
            },bt);
            
            if(this.buttons[i].text=='重置' && this.isSearch===true){
                this.addButtonHandler('重置',this.reset,this);
            }
        }
    },
    
    reCreateButtonBar   : function(){
        if(this.buttonBar!=undefined){
            var left = this.getBtBarLeft();             //获得起始左位置
            this.buttonBar.setLeft(left);
        }
    },

    createButtonBar     : function(){
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var left = this.getBtBarLeft();             //获得起始左位置
        
        this.buttonBar = new Sail.DIV({           //左移按钮
            left  : left,
            top   : 1,
            width : this.getBtBarWidth(),
            //border : "1px #ff0000 solid",
            height: this.titleBarHeight||23,
            parent: this.getOCD(),
            zIndex: 10
        });

        var html = this.getButtonBarHTML();
        this.buttonBar.setHTML(html);
        
        this.bindEvent2Button();
        
        return this.getBtBarWidth();
    },
    
    
    //===================================================================================
    //方法 ： some func for createBody and children 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getBodyHeight : function(){
        return this.height-((this.showTitle==true)?26:0)
    },
    
    createBody : function(config){              //创建body
        var bodyHeight = this.getBodyHeight();
        
        var bodyConfig = {
            left  : 0,
            top   : config.top-1||0,
            width : '100%',
            height: bodyHeight+1,
            parent: this.getOCD(),
            zIndex: 11
        };
        
        if(this.border===true){
            bodyConfig.border = '#99BBE8 1px solid';
        }
        //if(typeof this.border =='string'){
        //    bodyConfig.border = this.border;
        //}
        
        bodyConfig.style={};
        bodyConfig.style.overflow='hidden';
        this.body = new Sail.DIV(bodyConfig);

        //debugger;
        Sail.applyStyle(this.body.el,{
            filter:"progid:DXImageTransform.Microsoft.Fade(duration=0.4)"
        });

        //if(this.border=='right'){
        //    this.body.el.style.borderRight="#99BBE8 1px solid";
        //}

        
        //this.body.el.style.overflow='hidden';
        this.createChildren();
        //debugger;
        return this.body.getEl();
    },

    createChildren : function(){
        
        this.children=[];
        var bodyHeight = this.getBodyHeight();

        var childerConfig ={
            left  : 0,
            top   : 0,
            width : '100%',
            height: (bodyHeight-1)>0?bodyHeight-1:0,
            parent: this.body,
            border:'#ff0000 0px solid',
            zIndex: 10
        };
        var td = new Sail.DIV(childerConfig);
        td.el.style.backgroundColor = "#ffffff";
        td.el.style.overflow = 'auto';
        //td.setHTML("-0");
        this.children.push(td);
    },
    
    //===================================================================================
    //方法 ：  createWidgetElement
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createWidgetElement:function(){
        var date1 = new Date();

        //-------------------------------------------------------------------------------
        if(this.showTitle===true){
            var h_titleBar = this.createTitleBar();
            var h_splitBar = this.createSplitBar(h_titleBar);     
        }
        
        //-------------------------------------------------------------------------------
        var _top = h_titleBar+h_splitBar;
        this.createBody({top:_top-1});

        var date2 = new Date();

    },
    
    afterCreateWidget : function(){

        this.tabLayouts = new Sail.layoutConstructor({
            executor     : this.executor,
            items        : this.items,
            layoutConfig : this.layoutConfig,
            layout       : this.layout,
            parentDiv    : this.children[0],
            ownerFrame   : this.ownerFrame,
            ownerGroup   : this.ownerFrame.getChildren(),
            page         : this.ownerFrame.getBelongedPage(),
            widgetPrefix : this.ownerFrame.widgetPrefix,
            height       : this.getBodyHeight(),
            width        : this.body.getOffset().width,
            constructTo  : this
        });
        
        this.tabLayouts.height = this.getBodyHeight();
        this.tabLayouts.width  = this.body.getOffset().width;

        this.tabLayouts.doLayout(this.level);
    },

    
    lastFunc : function(){
    }  
});






﻿//=======================================================================================
//类名 ： Sail.widget.boxComponent
//说明 ： 编辑器输入选择类组件基类
//创建 ： 2009-09-17 21:30:00 
//变更 ： 
//
//=======================================================================================

Sail.widget.ext.button = function(config){
    this.defaultHeight = 23;
    //debugger;
    Sail.apply(this, config);
    //Sail.widget.ext.superclass.constructor.call(this);
    
}
Sail.extend(Sail.widget.ext.button,Sail.widget.ext,{
    
    enable : function(){
        this.el.enable();
    },
    disable : function(){
        this.el.disable();
    },
    getWidth : function(){
        return this.el.el.getBox().width;
    },
    getHeight : function(){
        return this.el.el.getBox().height;
    },
    setHeight: function(){
        
    },
    createWidgetElement:function(){
        var config ={
            text:"　"+this.title,
            iconCls:'x-btn-left mybutton',
            cls: 'x-btn-text-icon',
            renderTo:this.getOCD()
        };
        this.el = new Ext.Button(config);
    }
});

Sail.widget.ext.hidden = function(config){
    Sail.apply(this, config);
    Sail.widget.ext.superclass.constructor.call(this);
    this.value;
    this.defaultHeight = 23;
}
Sail.extend(Sail.widget.ext.hidden,Sail.widget.ext,{
    
    getValue : function(){
        return this.value;
    },
    setValue : function(v){
        this.value=v;
    },
    enable : function(){return;},
    disable : function(){return;},
	
    createWidgetElement:function(){
        
        var containerDiv = this.getOCD();                   //获得组件容器层
        //---------------------------------------------------------------------------------------------
        var titleDiv = document.createElement( "DIV" );     //创建标题容器
        containerDiv.appendChild( titleDiv );               //添加到包裹容器

        Sail.apply(titleDiv,{innerText:(this.title=="")?"":this.title+"：",align:"left",noWrap:true});  //定义对象
        Sail.apply(titleDiv.style,{color:"#000000",border:"0 #ababab solid",top:4,left:0,cursor:"default",position:"absolute",overflow:"hidden",marginLeft:3});
        this.hide();
        //---------------------------------------------------------------------------------------------
        //---------------------------------------------------------------------------------------------
        this.titleWidth = 0;
        this.titleDiv = titleDiv;
        this.inputDiv = titleDiv;
        this.el  = titleDiv;
    }
});



Sail.widget.ext.check = function(config){
    this.defaultHeight = 23;
    Sail.apply(this, config);
    Sail.widget.ext.superclass.constructor.call(this);
}
Sail.extend(Sail.widget.ext.check,Sail.widget.ext,{
    
    createWidgetElement:function(){
		this.el = new Ext.form.Checkbox({
			boxLabel : this.title,renderTo: this.getOCD()
		});
    }
});


Sail.widget.ext.checkGroup = function(config){
    this.uncheckValue = "-1";
    this.checkValue   = "1";
    this.showBorder   = false;
    
    Sail.apply(this, config);
    Sail.widget.ext.superclass.constructor.call(this);
    
    this.el = null;
    this.checkerList = [];
    this.value = "";
}
Sail.extend(Sail.widget.ext.checkGroup,Sail.widget.ext,{
    setHeight:function(h){
        this.height = h;
        //this.container.setHeight(h);
        //this.el.setHeight((this.type=='ext.myForm')?h-20:h);
    },
    
    bindData : function(){
        //debugger;
        var a = arguments;
        var d = (a.length==1)?a[0]:a[1];
        this.setValue(d);
    },
    
    getValue : function(){
        var values = [];
        for(var i=0;i<this.checkerList.length;i++){
            values.push((this.checkerList[i].checked)?this.checkValue:this.uncheckValue);
        }
        return (values.length>0)?values.join(','):"";
    },
    getSelected : function(){
        var selected = [];
        for(var i=0;i<this.checkerList.length;i++){
            if(this.checkerList[i].checked)
                selected.push(this.checkerList[i].value);
        }
        return selected;
    },
    select : function(value){
        var values = (value instanceof Array)?value:[value];
        
        for(var i=0;i<values.length;i++){
            if(this.checkerList[i].value==values[i])
                this.checkerList[i].checked = true;
        }
    },
    setValue : function(v){
        var values = v.split(',');
        for(var i=0;i<this.checkerList.length;i++){
            this.checkerList[i].checked = (values[i]!=undefined)?((values[i]==this.uncheckValue)?false:true):false;
        }
    },
    
    recreate2 : function(config){
        if(config.labels == undefined)  return;

        this.checkType  = (config.checkType!=undefined)?config.checkType:"check";
        this.labels     = config.labels;
        this.value      ='';        
        this.checkerList= [];
        
        this.inputDiv.innerHTML = "";
        
        for(var i=0;i<this.labels.length;i++){
            var checker = document.createElement( "INPUT" );
            checker.type=(this.checkType=='check')?'checkbox':'radio';
            checker.name = this.groupName;
            
            this.inputDiv.appendChild( checker );
            this.checkerList.push(checker);
            
            var label = document.createElement( "LABEL" );     
            label.innerHTML=this.labels[i]+"";
            this.inputDiv.appendChild( label );
        }
    },
    
    recreate : function(config){
        this.clear();
        //debugger;
        for(var i=0;i<config.labels.length;i++){
            var _type = (this.checkType=='check')?'checkbox':'radio';
            var _name = this.groupName;
            var _id   = (config.labelsValue==undefined)?"check__"+i:config.labelsValue[i];
            
            var _html="<INPUT TYPE='"+_type+"' value='"+_id+"' NAME='"+_name+"' >";
            var checker = document.createElement(_html);
            this.inputDiv.appendChild( checker );
            
            this.checkerList.push(checker);
            
            var label = document.createElement( "LABEL" );     
            label.innerHTML=config.labels[i]+"";
            this.inputDiv.appendChild( label );
            
            if(this.clickEvent!=undefined){
                Ext.get(checker).addListener('click',this.clickEvent);
            }
        }
        
        if(this.afterCreate!=undefined && typeof this.afterCreate=='function'){
            this.afterCreate.call('',this.checkerList);
        }
    },
    
    clear : function(){
        this.value      ='';        
        this.checkerList= [];
        this.inputDiv.innerHTML = "";
    },
    
    enable : function(){
        this.titleDiv.style.color = "#000000";
        for(var i=0;i<this.checkerList.length;i++){
            this.checkerList[i].disabled=false;
        }
        //this.el.enable();
    },
    disable : function(){
        this.titleDiv.style.color = "#a0a0a0";
        for(var i=0;i<this.checkerList.length;i++){
            this.checkerList[i].disabled=true;
        }
        //this.el.disable();
    },

    load : function(config){

        if(config.url         == undefined)  config.url         = this.url;
        if(config.root        == undefined)  config.root        = this.root;
        if(config.fieldText   == undefined)  config.fieldText   = this.fieldText;
        if(config.fieldValue  == undefined)  config.fieldValue  = this.fieldValue;
        if(config.labels      == undefined)  config.labels      = this.labels;
        if(config.labelsValue == undefined)  config.labelsValue = this.labelsValue;
        
        if(config.url==undefined) {
            Ext.Msg.alert('提示','没有找到数据源的URL！');
            return;
        }
        
        var theObj = this;
        var _callback = function(flag,getData){
            
            //---------------------------------------------------------
            //---------------------------------------------------------
            var itemList = sc.getDataObj2(getData,config.root); 
            if(itemList==null || itemList==undefined){
                Ext.Msg.alert('提示','没有找到root指定的数据集合！');
                return;
            }

            if(theObj.spliceFunc!=undefined && typeof(theObj.spliceFunc)=='function'){
                for(var i=itemList.length-1;i>=0;i--){
                    if(theObj.spliceFunc(itemList[i]))
                        itemList.splice(i,1);
                }
            }
            
            //---------------------------------------------------------
            //---------------------------------------------------------
            var createConfig = {labels:[],labelsValue:[]};
            if(config.labels!=undefined){
                for(var i=0;i<config.labels.length;i++){
                    createConfig.labels.push(config.labels[i]);
                    createConfig.labelsValue.push(config.labelsValue[i]);
                }
            }
            
            //---------------------------------------------------------
            //---------------------------------------------------------
            for(var i=0;i<itemList.length;i++){
                createConfig.labels.push(itemList[i][config.fieldText]);
                createConfig.labelsValue.push(itemList[i][config.fieldValue]);
            }
            
            //---------------------------------------------------------
            //---------------------------------------------------------
            theObj.recreate(createConfig);
        };

        sc.postData(config.url,{},_callback);
            
    },
    
    createWidgetElement:function(){

        var containerDiv = this.getOCD();                   //获得组件容器层
        //---------------------------------------------------------------------------------------------
        var titleDiv = document.createElement( "DIV" );     //创建标题容器
        containerDiv.appendChild( titleDiv );               //添加到包裹容器

        var _innerText = (this.title=="")?"":this.title+"：";
        var _tmpText = this.mustMark+((_innerText.indexOf('*')!=-1)?_innerText.replace("*",''):_innerText);
        var _innerHTML  =(this.allowBlank!=undefined && this.allowBlank==false)?_tmpText:((_innerText.indexOf('*')!=-1)?_tmpText:_innerText);
        Sail.apply(titleDiv,{innerHTML:_innerHTML,align:"left",noWrap:true});  //定义对象
        
        Sail.apply(titleDiv.style,{color:"#000000",border:"0 #ababab solid",top:4,left:0,cursor:"default",position:"absolute",overflow:"hidden",marginLeft:3});
        this.titleWidth = titleDiv.offsetWidth;             //获得标题实际尺寸
        
        //-----------------------------------------------------------------------------------------
        //定义 数据层 （需要根据折行与否计算位置及尺寸）
        //-----------------------------------------------------------------------------------------
        var inputDivLeft   = this.titleWidth + 4;;
        var inputDivWidth  = this.width - this.titleWidth -7;
        var inputDivHeight = this.height;
        this.boxWidth = inputDivWidth;
        
        var inputDiv = document.createElement( "DIV" );     //创建值容器
        containerDiv.appendChild( inputDiv );               //添加到包裹容器
        var _border = (this.showBorder===true)?'1px #B5B8C8 solid':'0px #B5B8C8 solid';
        
        Sail.apply(inputDiv.style,{border:_border,left:inputDivLeft,top:0,width:inputDivWidth,height:this.height,position:"absolute",overflow:"hidden"});
        
        //---------------------------------------------------------------------------------------------
        var _config ={width:inputDivWidth,renderTo:inputDiv};
        if(this.allowBlank!=undefined) _config.allowBlank  = this.allowBlank;

        this.groupName = inputDiv.uniqueID+"_group";
        this.checkType = (this.checkType==undefined)?"check":this.checkType;

        this.root       = (this.root==undefined)?"dataset.simplecombobox":this.root;
        this.fieldText  = (this.fieldText==undefined)?"text":this.fieldText;
        this.fieldValue = (this.fieldValue==undefined)?"value":this.fieldValue;

        if(this.labels !=undefined){
            for(var i=0;i<this.labels.length;i++){

                var _type = (this.checkType=='check')?'checkbox':'radio';
                var _name = this.groupName;
                var _id   = (this.labelsValue==undefined)?"check__"+i:this.labelsValue[i];
                
                var _html="<INPUT TYPE='"+_type+"' value='"+_id+"' NAME='"+_name+"' >";
                var checker = document.createElement(_html);
                inputDiv.appendChild( checker );
                
                this.checkerList.push(checker);
                
                var label = document.createElement( "LABEL" );     
                label.innerHTML=this.labels[i]+"";
                inputDiv.appendChild( label );
                
                if(this.clickEvent!=undefined){
                    Ext.get(checker).addListener('click',this.clickEvent);
                }
            }
        }
        
        this.el = {};
        
        //---------------------------------------------------------------------------------------------
        this.titleDiv = titleDiv;
        this.inputDiv = inputDiv;

        //---------------------------------------------------------------------------------------------
        var theObj = this;
        if(this.url!=undefined){
            var _callback = function(flag,getData){
                
                var itemList = sc.getObjFromPostData(getData,theObj.root);
                if(itemList==null || itemList==undefined)
                    return;

                if(theObj.spliceFunc!=undefined && typeof(theObj.spliceFunc)=='function'){
                    for(var i=itemList.length-1;i>=0;i--){
                        if(theObj.spliceFunc(itemList[i]))
                            itemList.splice(i,1);
                    }
                }
                
                for(var i=0;i<itemList.length;i++){
    
                    var _type = (theObj.checkType=='check')?'checkbox':'radio';
                    var _name = theObj.groupName;
                    var _id   = itemList[i][theObj.fieldValue];
                    var _html="<INPUT TYPE='"+_type+"' value='"+_id+"' NAME='"+_name+"' >";
                    var checker = document.createElement(_html);
                    
                    theObj.inputDiv.appendChild( checker );
                    theObj.checkerList.push(checker);
                    
                    var label = document.createElement( "LABEL" );     
                    label.innerHTML = itemList[i][theObj.fieldText];
                    theObj.inputDiv.appendChild( label );
                    
                    if(theObj.clickEvent!=undefined){
                        Ext.get(checker).addListener('click',theObj.clickEvent);
                    }
                    
                }
            };
            sc.postData(this.url,{},_callback);
        }

    }
});


Sail.widget.ext.radio = function(config){
    this.defaultHeight = 23;
    Sail.apply(this, config);
    Sail.widget.ext.superclass.constructor.call(this);
}
Sail.extend(Sail.widget.ext.radio,Sail.widget.ext,{
    
    createWidgetElement:function(){
		this.el = new Ext.form.Radio({
		    boxLabel : this.title,name : this.groupID,renderTo: this.getOCD()
		});
    }
});


﻿
/**************************************************************************************************
* 对象： VMLCurve
* 说明： VML画曲线图
*
**************************************************************************************************/
function VMLCurve(config){
	
    this.firstCreateFlag = true;
    
	this.toolTips    = "";				// 提示信息
	this.configXPerValue = 0;
    this.configYPerValue = 0;
    this.configXMinValue = 0;
    this.configYMinValue = 0; 
	
	this.OriginXValue = 0;				// 圆点坐标
	this.OriginYValue = 0;
	
	//定义区域参数
	this.group				= null;		// v:group
	this.n 					= 1;			// 倍数
	this.gpWidth			= 700;		// Width
	this.gpHeight			= 350;		// Height
	
	this.configXTextLeft	= -10;		// 定义 X轴坐标值左边离坐标距离
	this.configXTextTop 	= 5;		// 定义 X轴坐标值上方离X轴的距离
	
	this.configYLeft 		= 60;		// 定义 Y轴距对象左边的距离
	this.configYTextRight	= 55;		// 定义 Y轴坐标值离Y轴右边的距离
	this.configYTextBottom 	= 10;		// 定义 Y轴坐标值离坐标下边距离
	
	//X轴值
	this.configXValue = new Array();
	//Y轴值
	this.configYValue = new Array();
	
	// Init BackGround
	this.Background		= null;	
	this.bgColor		= "#efefef";		// BackGround Color //C4E1FF
	
	
	//设置点线的属性
	this.PointRadius = 5; 					//圆点的半径大小
	this.LineSize    = 2;                  	//线的大小
	this.PointColor  = "#FF6600";			//点的颜色
	this.LineColor   = "#FF6600";			//线的颜色
	
	this.Points = "";
	this.PreviousPointY = 0;
	this.PointsYCount   = 0;
 
    this.pointObjs =[];
    this.lineObjs  =[];
    this.histogramObjs = [];
    this.hExtrusion = [];
    
    this.xTableLine = [];
    this.yTableLine = [];
    this.xText = [];
    this.yText = [];
    
    this.XCoordinateLine = null;
    this.YCoordinateLine = null;
    
    this.needOriginValue = true;
    
    
    this.xScaleHeight = 50;
    this.xScaleTextDirection = "h";
    
    //this.showText = config.showText;
    //this.objDiv = config.objDiv;				// obj
    //this.parentName = config.parentName;
    Sail.apply(this,config);
    
	this.groupID = "group_"+this.objDiv.uniqueID;
    this.bgID    = "bg_"+this.objDiv.uniqueID;

 }

VMLCurve.prototype.hideElGroup = function(groupName){
    for(var i=0,len = this[groupName].length;i<len;i++)    
        this[groupName][i].style.display='none';
    this[groupName]= [];            
}

VMLCurve.prototype.removeElGroup = function(groupName){
    for(var i=0,len = this[groupName].length;i<len;i++)    
        this.group.removeChild(this[groupName][i]);
        //this[elName][i].style.display='none';
    this[groupName]= [];            
}

// Init
VMLCurve.prototype.init = function(strObj,strTitle){
	
	this.gpcX			= this.gpWidth/this.n;			// coordsize X
	this.gpcY			= this.gpHeight/this.n;			// coordsize Y
	//this.gpcY = this.gpcY*2;
	this.configXLen	  	= this.gpWidth - this.configYLeft*2+20;	// 定义 X轴长度
	this.configYLen	  	= this.gpHeight- this.xScaleHeight;		// 定义 Y 轴长度
	this.configXNum		= this.configXValue.length;		// X轴刻度数
	this.configYNum		= this.configYValue.length;		// Y轴刻度数
	
    this.configXTop		= this.configYLen+20;			//定义 X轴距对象上边的距离
	
	this.configXPerLen	= str2Float((this.configXLen-20)/this.configXNum,2); //定义 X轴每刻度长度
	this.configYPerLen	= str2Float((this.configYLen-20)/this.configYNum,2); //定义 Y轴每刻度长度

    this.configXPerLen  = (this.configXNum==1)?this.configXPerLen/2:this.configXPerLen;
	
	//初始化背景参数
	this.bgWidth		= this.gpWidth;		// Height
	this.bgHeight		= this.gpHeight;	// Width
	
	if(this.configYPerValue!=0){ 
        var tempArr = new Array(this.configYNum);
        for(var i=0;i<this.configYNum;i++){
        	tempArr[i] = str2Float(this.configYMinValue+this.configYPerValue*i,2);
        }
        this.configYValue = tempArr; 
	}
    else {
        this.configYPerValue = str2Float((this.configYValue[this.configYNum]-this.configYMinValue)/this.configYNum,2); 
    } 
    
   if(this.configXPerValue!=0){ 
        var tempArr = new Array(this.configXNum);
        for(var i=0;i<this.configXNum;i++){
        	tempArr[i] = str2Float(this.configXMinValue+this.configXPerValue*i,2);
        }
        this.configXValue = tempArr;  
	}else{
         //this.configXPerValue = str2Float((this.configXValue(this.configXNum)-this.configXMinValue)/this.configXNum,2); 
    } 
	
    this.configYValue  = this.configYValue.reverse();	//倒序数组 
	this.createGroup();
	this.createBackgroud();
	this.createCoordinate();
	this.createXTableLine();
	this.createYTableLine();
	
	//this.setTitle(strTitle);
	this.strObj = strObj;
}

VMLCurve.prototype.reInit = function(){
	this.gpcX			= this.gpWidth/this.n;			// coordsize X
	this.gpcY			= this.gpHeight/this.n;			// coordsize Y
	
	this.configXLen	  	= this.gpWidth - this.configYLeft*2+20;	// 定义 X轴长度
	this.configYLen	  	= this.gpHeight- this.xScaleHeight;	    // 定义 Y 轴长度
	this.configXNum		= this.configXValue.length;		// X轴刻度数
	this.configYNum		= this.configYValue.length;		// Y轴刻度数
	
    this.configXTop		= this.configYLen+20;			//定义 X轴距对象上边的距离
	
	this.configXPerLen	= str2Float((this.configXLen-20)/this.configXNum,2); //定义 X轴每刻度长度
	this.configYPerLen	= str2Float((this.configYLen-20)/this.configYNum,2); //定义 Y轴每刻度长度

    this.configXPerLen  = (this.configXNum==1)?this.configXPerLen/2:this.configXPerLen;

	//this.configXValue;
	
	//初始化背景参数
	this.bgWidth		= this.gpWidth;		// Height
	this.bgHeight		= this.gpHeight;	// Width
	
	if(this.configYPerValue!=0){ 
        var tempArr = new Array(this.configYNum);
        for(var i=0;i<this.configYNum;i++){
        	tempArr[i] = str2Float(this.configYMinValue+this.configYPerValue*i,2);
        }
        this.configYValue = tempArr; 
	}
    else {
        this.configYPerValue = str2Float((this.configYValue[this.configYNum]-this.configYMinValue)/this.configYNum,2); 
    } 
    
   if(this.configXPerValue!=0){ 
        var tempArr = new Array(this.configXNum);
        for(var i=0;i<this.configXNum;i++){
        	tempArr[i] = str2Float(this.configXMinValue+this.configXPerValue*i,2);
        }
        this.configXValue = tempArr;  
	}else{
         //this.configXPerValue = str2Float((this.configXValue(this.configXNum)-this.configXMinValue)/this.configXNum,2); 
    } 
	
    this.configYValue  = this.configYValue.reverse();	//倒序数组 
    
    this.Background.style.width = this.bgWidth;
    this.Background.style.height = this.bgHeight;
    this.createCoordinate();
	this.createXTableLine();
	this.createYTableLine();
	
}

//建立画图区域
VMLCurve.prototype.createGroup = function() {
    if(document.getElementById(this.groupID)==undefined){
        this.firstCreateFlag = true;
    }else{
        this.firstCreateFlag = false;
    }
    if(this.firstCreateFlag==true){
	    this.group = document.createElement("<v:group ID='"+this.groupID+"' coordOrig='0,-"+this.gpcY+"' coordsize=\""+this.gpcX+","+this.gpcY+"\" style=\"z-index:-10;width:"+this.gpWidth+"px;height:"+this.gpHeight+"px\">");
	    this.objDiv.insertBefore(this.group);
    }else{
    }
}

//填充背景
VMLCurve.prototype.createBackgroud = function() {
    //this.bgWidth;
    //debugger;
    if(this.firstCreateFlag==true){
	    this.Background = document.createElement("<v:rect ID='"+this.bgID+"' fillcolor=\"white\" strokecolor='#ffffff' style=\"z-index:-8;width:"+this.bgWidth+"px;height:"+this.bgHeight+"px\" />");
	    this.Background.insertBefore(document.createElement("<v:fill rotate=\"t\" type=\"gradient\" color2=\""+this.bgColor+"\" />"));
	    //this.Background.insertBefore(document.createElement("<v:shadow on=\"t\" type=\"single\" color=\"silver\" offset=\"3pt,2pt\" />"));
	    this.group.insertBefore(this.Background);
    }else{
        var bg = document.getElementById(this.bgID);
        bg.style.width  = this.bgWidth;
        bg.style.height = this.bgHeight;
    }
}

//建立坐标轴
VMLCurve.prototype.createCoordinate = function() {
    //debugger;
	if(this.XCoordinateLine!=null){
	    this.XCoordinateLine.style.display='none';
	}
	if(this.YCoordinateLine!=null){
	    this.YCoordinateLine.style.display='none';
	}
	
	var pointX1 = this.configYLeft + "," + this.configXTop;
	var pointX2 = this.configYLeft+this.configXLen + "," + this.configXTop;
	var pointY1 = pointX1;
	var pointY2 = this.configYLeft + "," + eval(this.configXTop-this.configYLen);
	
	this.XCoordinateLine = this.createCoordinateLine(pointY1,pointX2);      //X轴
	this.YCoordinateLine = this.createCoordinateLine(pointY1,pointY2);      //Y轴
	this.setOriginValue(this.OriginXValue,this.OriginYValue);
}

//建立坐标线
VMLCurve.prototype.createTableLine = function(xPoint,yPoint,sTableColor,mode){
	var tempLine = document.createElement("<v:line from=\""+xPoint+"\" to=\""+yPoint+"\" strokeColor=\""+sTableColor+"\" style=\"Z-INDEX:8;POSITION:absolute;/>");
	this.group.insertBefore(tempLine);
	var type="Solid";
	tempLine.insertBefore(document.createElement("<v:stroke dashstyle=\""+type+"\" />"));

	if(mode==="x"){
	    this.xTableLine.push(tempLine);
	}else{
	    this.yTableLine.push(tempLine);
	}
}


//画坐标轴线
VMLCurve.prototype.createCoordinateLine = function(xPoint,yPoint){
	var tempLine = document.createElement("<v:line from=\""+xPoint+"\" to=\""+yPoint+"\" strokeColor=\"#FF6600\" strokeweight=\"1px\" style=\"Z-INDEX:8;POSITION:absolute;\"/>");
	this.group.insertBefore(tempLine);
	tempLine.insertBefore(document.createElement("<v:stroke  EndArrow=\"classic\" />"));
	return tempLine;
}


VMLCurve.prototype.createText2 = function(xLeft,xTop,sText,sClass,mode,push2) {

    var xPoint = xLeft+","+xTop;
    var yPoint = xLeft+","+(xTop+50);
    var sTableColor = "#FF6600";
	var tempLine = document.createElement("<v:line from=\""+xPoint+"\" to=\""+yPoint+"\" strokeColor=\""+sTableColor+"\" stroked='f' filled='t' stroked='f' strokecolor='#FFFF66'  fillcolor='black' style=\"Z-INDEX:8;POSITION:absolute;/>");

	//var to = document.createElement("<v:line style='Z-INDEX:9999;position: absolute; left: "+xLeft+";top: "+xTop+"; ' stroked='f' filled='t' fillcolor='black' to='"+xLeft+" "+xTop+"'></v:line>");
	this.group.insertBefore(tempLine);
	
	tempLine.insertBefore(document.createElement("<v:path textpathok='t'/><v:textpath on='t' fitpath='t' string='文字'/>"));
	//var to2 = document.createElement("<v:path textpathok='t'/><v:textpath on='t' fitpath='t' string='文字的颜色特效'/>");
	//to.insertBefore(to2);
	return;

	
	//debugger;
	if(push2=="y")
	    var tempObj = document.createElement("<P class=\""+sClass+"\" align='right' style=\"Z-INDEX:8;LEFT:"+xLeft+"px;width:50px;POSITION:absolute;TOP:"+xTop+"px;\"/>");
	else
	    var tempObj = document.createElement("<P class=\""+sClass+"\" align='right' style=\"Z-INDEX:8;LEFT:"+xLeft+"px;POSITION:absolute;TOP:"+xTop+"px;\"/>");
	    
	tempObj.innerHTML = sText;
	this.group.insertBefore(tempObj);
	
	if(mode===true){
	    tempObj.style.left = xLeft-tempObj.offsetWidth-(this.configXPerLen-tempObj.offsetWidth)/2;
	}
	
	if(push2!=undefined){
	    if(push2=="x") this.xText.push(tempObj);
	    else this.yText.push(tempObj);
	}
	//alert(tempObj.offsetWidth);
	//debugger;
}

//创建文本提示信息
VMLCurve.prototype.createText = function(xLeft,xTop,sText,sClass,mode,push2) {
	//debugger;
	if(push2=="y")
	    var tempObj = document.createElement("<P class=\""+sClass+"\" align='right' style=\"Z-INDEX:8;LEFT:"+xLeft+"px;width:50px;POSITION:absolute;TOP:"+xTop+"px;\"/>");
	else
	    var tempObj = document.createElement("<P class=\""+sClass+"\" align='right' style=\"Z-INDEX:8;LEFT:"+xLeft+"px;POSITION:absolute;TOP:"+xTop+"px;\"/>");
	    
	tempObj.innerHTML = sText;
	this.group.insertBefore(tempObj);
    
    var w = Sail.getLabelWidth(sText);
	if(mode===true){
	    tempObj.style.left = xLeft-w-(this.configXPerLen-w)/2;
	}
	
	if(push2!=undefined){
	    if(push2=="x") this.xText.push(tempObj);
	    else this.yText.push(tempObj);
	}
	//alert(tempObj.offsetWidth);
	//debugger;
}

VMLCurve.prototype.getAcclivitousText = function(text,index) {
    var color = (index%2==0)?"#000000":"#666666";

    var len = Sail.getLabelWidth(text,'normal 10px verdana');	 
    len = Math.sqrt(len*len/2);

    var html = [];
    html.push("<v:polyline style='POSITION:absolute;' fillcolor='"+color+"' strokecolor='"+color+"' points='0,0 "+len+","+len+"'>");
    html.push("<v:Path textpathok='True'/>");
    html.push("<v:Textpath on='True' style='font:normal 10px verdana;'  string='");
    html.push(text);
    html.push("'/></v:polyline>");
    return html.join('');
}

VMLCurve.prototype.createTextAcclivitous = function(xLeft,xTop,sText,sClass,mode,push2,index) {
	//debugger;
	if(push2=="y"){
	    var tempObj = document.createElement("<P class=\""+sClass+"\" align='right' style=\"Z-INDEX:8;LEFT:"+xLeft+"px;width:50px;font-weight:bold;POSITION:absolute;TOP:"+xTop+"px;\"/>");
	}else{
	    var tempObj = document.createElement("DIV");
	    tempObj.style.position = "absolute";
	    tempObj.style.left = xLeft;
	    tempObj.style.top = xTop;
	    tempObj.style.width = 10;
	    tempObj.style.height = 80;
	    //tempObj.style.border = "1px #ff0000 solid";
	    
	    //var tempObj = document.createElement("<P class=\""+sClass+"\" align='right' style=\"Z-INDEX:8;LEFT:"+xLeft+"px;POSITION:absolute;TOP:"+xTop+"px;\"/>");
	}
	
    //if(index==0) debugger;   
	tempObj.innerHTML = this.getAcclivitousText(sText,index);
	this.group.insertBefore(tempObj);
	
	if(mode===true){
	    tempObj.style.left = xLeft-tempObj.offsetWidth-(this.configXPerLen-tempObj.offsetWidth)/2;
	}
	
	if(push2!=undefined){
	    if(push2=="x") this.xText.push(tempObj);
	    else this.yText.push(tempObj);
	}
	//alert(tempObj.offsetWidth);
	//debugger;
}
// 创建X坐标网格线
VMLCurve.prototype.createXTableLine = function(){
	var x1,y1,x2,y2,point1,point2,sTableColor;
	sTableColor = "#CCCCCC";
	
	//if(this.isGroup===true) debugger;
	//debugger;
	for(var i=0;i<this.configXValue.length;i++){
		x1 = eval(this.configYLeft + this.configXPerLen*(i+1));
		y1 = eval(this.configXTop-this.configXHeight);//eval(this.configXTop-this.configYLen)+10;
		x2 = x1;
		y2 = eval(this.configXTop+0);
		point1 = x1 + "," + y1; 
		point2 = x2 + "," + y2;
    	this.createTableLine(point1,point2,'#FF6600',"x");
        //debugger;
        if(this.isGroup===true){
            if(this.configXTextMode==="middleSpace")
        	    this.createText(x1,this.configXTop+this.configXTextTop+16,this.configXValue[i],"pBlack",true,"x");
        	else
        	    this.createText(x1+this.configXTextLeft,this.configXTop+this.configXTextTop+16,this.configXValue[i],"pBlack",false,"x");
        }else{
            if(this.configXTextMode==="middleSpace"){

        	    if(this.xScaleTextDirection==="italic"){
        	        this.createTextAcclivitous(x1,this.configXTop+this.configXTextTop,this.configXValue[i],"pBlack",true,"x",i);
        	    }else if(this.xScaleTextDirection==="none"){
        	        ;//数据过多，不显示X轴刻度文本
        	    }else{
        	        this.createText(x1,this.configXTop+this.configXTextTop,this.configXValue[i],"pBlack",true,"x",i);
        	    }
        	}
        	else{
        	    var len = Sail.getLabelWidth(this.configXValue[i]);
        	    var len = -1*(len/2);
        	    //len = (this.graphType==="polyLine")?0:len;
        	    
        	    if(this.xScaleTextDirection==="italic"){
        	        this.createTextAcclivitous(x1,this.configXTop+this.configXTextTop,this.configXValue[i],"pBlack",false,"x",i);
        	    }else if(this.xScaleTextDirection==="none"){
        	        ;//数据过多，不显示X轴刻度文本
        	    }else{
        	        this.createText(x1+len,this.configXTop+this.configXTextTop,this.configXValue[i],"pBlack",false,"x",i);
        	    }
        	}
        }
        /*var xtopAdd = (this.isGroup===true)?16:0;
        if(this.configXTextMode==="middleSpace")
    	    this.createText(x1,this.configXTop+this.configXTextTop+xtopAdd,this.configXValue[i],"pBlack",true,"x");
    	else
    	    this.createText(x1+this.configXTextLeft,this.configXTop+this.configXTextTop+xtopAdd,this.configXValue[i],"pBlack",false,"x");
    	*/    
	}
}

//创建Y轴坐标网格线
VMLCurve.prototype.createYTableLine = function(){
	var x1,y1,x2,y2,point1,point2,sTableColor;
	for(var i=0;i<this.configYValue.length;i++){
		x1 = eval(this.configYLeft - 0);
		y1 = eval(this.configXTop - this.configYPerLen*(i+1));
		x2 = eval(this.configYLeft + this.configXLen - 10);
		y2 = y1;
		point1 = x1 + "," + y1; 
		point2 = x2 + "," + y2;
    	if(this.configYValue[this.configYValue.length-i-1]=="C2") sTableColor="#FF9900";
		else sTableColor = "#CCCCCC";
		this.createTableLine(point1,point2,sTableColor,"y");
		y1-=2;
		//debugger;
		this.createText(this.configYLeft-this.configYTextRight,y1-this.configYTextBottom,this.configYValue[this.configYValue.length-i-1],"pBlack",false,"y");
	}
}


//设置标题
VMLCurve.prototype.setTitle = function(strTitle){
	var tempObj = document.createElement("<div class=\"Title\" style=\"POSITION:absolute;Z-INDEX:9;LEFT:"+40+"px;TOP:"+(this.configXTop+40)+"px;width:"+(this.configXLen)+"px;height:"+(this.gpHeight-this.configXTop-20)+";/>");
	tempObj.innerHTML = strTitle;
	this.group.insertBefore(tempObj);
}

// 画圆点坐标
VMLCurve.prototype.setOriginValue = function(x,y){
	if(this.needOriginValue===true)
	    this.createText(this.configYLeft+this.configXTextLeft,this.configXTop+this.configXTextTop,x,"pBlack");
	//this.createText(this.configYLeft-this.configYTextRight,this.configXTop-this.configYTextBottom,y,"pBlack");
}


// 设置圆点坐标属性
VMLCurve.prototype.setPointsProp = function(sPointRadius,sLineSize,sPointColor,sLineColor){
	this.PointRadius = sPointRadius; 		//圆点的半径大小
	this.LineSize    = sLineSize;          	//线的大小
	this.PointColor  = sPointColor;			//点的颜色
	this.LineColor   = sLineColor;			//线的颜色
}


// 设置纵坐标的值
VMLCurve.prototype.setPointsValue = function(xValueArr,yValueArr,sValueArr){
    var sValue  = "";
    var xValue  = 0;
	var yValue  = 0;
	var tempLen = 0;
	var thisX   = 0; 
	var thisY   = 0; 
	var tempX   = 0;
    var tempY   = 0; 
	this.pointObjs.push([]);

	for(var i=0;i<xValueArr.length;i++){
        thisX   = str2Float(xValueArr[i],2); 
        thisY   = str2Float(yValueArr[i],2); 
        sValue  = sValueArr[i]; 
        
        //tempX   = str2Float((thisX - this.OriginXValue)/this.configXPerValue,2);
		tempY   = str2Float((thisY - this.OriginYValue)/this.configYPerValue,2);
		xValue  = str2Float(this.configYLeft + str2Float(thisX*this.configXPerLen,2),2);
		yValue  = str2Float(this.configXTop - str2Float(tempY*this.configYPerLen,2),2);
		
		this.Points = this.Points + xValue + "," + yValue + " ";	
		this.createPoint(xValue,yValue,sValue);
	}
	
	this.createCurveLine();
	    
	this.PreviousPointY = 0;
	this.Points         = 0;
	this.PointsYCount   = 0;
}








//创建一组柱状图
VMLCurve.prototype.createHistograms = function(xValueArr,yValueArr,titles,color,isAdjust){
    //debugger;
    var xValue  = 0;
	var yValue  = 0;
	var tempLen = 0;
	
	var thisX   = 0; 
	var thisY   = 0; 
	var tempX   = 0;
    var tempY   = 0; 
    
    var valueY  = 0;
    var title   = "";
    
    if(isAdjust===false){
        this.hwidgets={}; 
    }
    
    if(this.histogramTemplet==undefined)
        this.createHistogramTemplet();
    
	for(var i=0;i<xValueArr.length;i++){
        xValue = [];
        yValue = [];
        thisX = [];
        thisY = [];
        tempY = [];
        title = [];
        valueY = [];
        for(var j=0;j<yValueArr[i].length;j++){
            thisX.push(str2Float(xValueArr[i],2)); 
            thisY.push(str2Float(yValueArr[i][j],2)); 

    		tempY.push(str2Float((thisY[j] - this.OriginYValue)/this.configYPerValue,2));
    		xValue.push(str2Float(this.configYLeft + str2Float(thisX[j]*this.configXPerLen,2),2));
    		yValue.push(str2Float(this.configXTop - str2Float(tempY[j]*this.configYPerLen,2),2));
    		
    		valueY.push(thisY[j]);
    		title.push(titles[i][j]);
	    }
        this.createHistogramGroup(xValue,yValue,thisX,tempY,title,color,valueY,isAdjust,i);
	}
};

VMLCurve.prototype.createHistogramTemplet = function(){
        var py = 1;
        var px = 1;
        var hwidth = 30;
        var h = 1;
        var color = "#ffffff";
        var _left = 0;
        var w = 0;
        
        var newShape= document.createElement("<v:rect "+
            "style='cursor:hand;position:absolute;z-index:9;"+
            "left:"+py+";top:"+px+";WIDTH:" + hwidth + "px;HEIGHT:"+h+"px;' "+
            "fillcolor='" + color + "' ></v:rect>");

        var textHtml="<v:TextBox inset='"+_left+"px,"+w+"px,0pt,0pt' "+
            "style='color:#FD4302;font-size:9pt;'>"+
            "<div style='writing-mode: tb-rl;position:absolute;Z-INDEX:20' align='center'></div>"+
            "</v:TextBox>";
        newShape.innerHTML=textHtml;

        this.histogramTemplet = newShape;

        
        var tmpO = document.createElement("<o:extrusion on='true' backdepth='0'/>");
        this.extrusionTemplet = tmpO;
};

VMLCurve.prototype.createHistogramGroup = function(sLeft,sTop,thisX,tempY,title,color,yValueArr,isAdjust,xIndex){
    //debugger;
    var count   = sLeft.length;
    var space1  = (this.space1==undefined)?10:this.space1;
    var hwidth  = (this.hwidth==undefined)?30:this.hwidth;
    var space2  = parseInt((this.configXPerLen - hwidth*count-space1*(count-1))/2,10);
    
    var nowLeft = space2;
    
    //debugger;
    for(var i=0;i<sLeft.length;i++){
        var left = sLeft[i]-this.configXPerLen+nowLeft;
        this.createHistogram(left,sTop[i],hwidth,thisX[i],tempY[i],title[i],color[i],yValueArr[i],isAdjust,xIndex,i);
        nowLeft+=hwidth+space1;
    }
};


VMLCurve.prototype.createHistogram = function(sLeft,sTop,hwidth,thisX,tempY,title,color,oldValue,isAdjust,xIndex,yIndex){
    //debugger;
    var py = sLeft;
    var px = sTop -0;
    var h = tempY*this.configYPerLen;
    var id = "histogram_"+xIndex+"_"+yIndex;
    
    if(isAdjust===true){
        var hg = this.hwidgets[id];//document.getElementById(id);
        hg.style.left   = py;
        hg.style.top    = px;
        hg.style.width  = hwidth;
        hg.style.height = h;
    }else{
        
        var newShape = this.histogramTemplet.cloneNode(true);
        newShape.style.left   = py;
        newShape.style.top    = px;
        newShape.style.width  = hwidth;
        newShape.style.height = h;
        newShape.fillcolor    = color;
        
        var oldColor = color;
        var pName = this.parentName;
        
        Ext.get(newShape).on('mouseover',function(){
            //debugger;
            this.fillcolor='#ff0000';
            if($(pName)!=undefined){
                $(pName).showMsg(title);
            }
        },newShape);

        Ext.get(newShape).on('mouseout',function(){
            this.fillcolor=oldColor;
            if($(pName)!=undefined){
                $(pName).hideMsg();
            }
        },newShape);
        
//        var newShape= document.createElement("<v:rect id='"+id+"'"+
//            "onmouseover=\"this.fillcolor='#ff0000';if($('"+this.parentName+"')!=undefined){$('"+this.parentName+"').showMsg('"+title+"');}\" "+
//            "onmouseout=\"this.fillcolor='"+color+"';if($('"+this.parentName+"')!=undefined){$('"+this.parentName+"').hideMsg();}\" "+
//            "style='cursor:hand;position:absolute;z-index:9;"+
//            "left:"+py+";top:"+px+";WIDTH:" + hwidth + "px;HEIGHT:"+h+"px;' "+
//            "fillcolor='" + color + "' ></v:rect>");
//        
//        if(this.showText===true){
//            var w = -1*(Sail.getLabelWidth(oldValue)+4);
//            
//            var _left = (hwidth-9)/2;
//            _left=(_left<1)?_left-1:_left;
//            
//            var textHtml="<v:TextBox inset='"+_left+"px,"+w+"px,0pt,0pt' "+
//                "style='color:#FD4302;font-size:9pt;'>"+
//                "<div style='writing-mode: tb-rl;position:absolute;Z-INDEX:20' align='center'>"+oldValue+"</div>"+
//                "</v:TextBox>";
//            newShape.innerHTML=textHtml;
//        }
        
        if(this.showText===true){
            var w = -1*(Sail.getLabelWidth(oldValue)+4);
            var _left = (hwidth-9)/2;
            _left=(_left<1)?_left-1:_left;
            newShape.children[0].inset = _left+"px,"+w+"px,0pt,0pt";
            newShape.children[0].children[0].innerText = oldValue;
        }

        
        var tmpO = this.extrusionTemplet.cloneNode(true);
    	this.group.insertBefore(newShape);
    	newShape.insertBefore(tmpO);
    
        this.hwidgets[id] = newShape;
        
    	this.histogramObjs.push(newShape);
    	this.hExtrusion.push(tmpO);
    }
};

VMLCurve.prototype.hideHistograms = function(){
    if(arguments.length==1&&arguments[0]===true){
        this.removeElGroup("histogramObjs");
        //this.removeElGroup("hExtrusion");
        this.removeElGroup("xTableLine");
        this.removeElGroup("yTableLine");
        this.removeElGroup("xText");
        this.removeElGroup("yText");
    }else{
        this.hideElGroup("histogramObjs");
        this.hideElGroup("hExtrusion");
        this.hideElGroup("xTableLine");
        this.hideElGroup("yTableLine");
        this.hideElGroup("xText");
        this.hideElGroup("yText");
    }
};

VMLCurve.prototype.hideHistogramCoordinate = function(){
    if(arguments.length==1&&arguments[0]===true){
        this.removeElGroup("xTableLine");
        this.removeElGroup("yTableLine");
        this.removeElGroup("xText");
        this.removeElGroup("yText");
    }else{
        this.hideElGroup("xTableLine");
        this.hideElGroup("yTableLine");
        this.hideElGroup("xText");
        this.hideElGroup("yText");
    }
};











VMLCurve.prototype.createPolyLines = function(){
};

VMLCurve.prototype.hideCoordinate = function(){
    if(arguments.length==1&&arguments[0]===true){
        this.removeElGroup("xTableLine");
        this.removeElGroup("yTableLine");
        this.removeElGroup("xText");
        this.removeElGroup("yText");
    }else{
        this.hideElGroup("xTableLine");
        this.hideElGroup("yTableLine");
        this.hideElGroup("xText");
        this.hideElGroup("yText");
    }
};

VMLCurve.prototype.hidePolyLine = function(){
    if(arguments.length==1&&arguments[0]===true){
        for(var i=0,len = this.pointObjs.length;i<len;i++){
            for(var j=0;j<this.pointObjs[i].length;j++)
                this.group.removeChild(this.pointObjs[i][j]);
        }
        this.pointObjs= [];            
        
        
        this.removeElGroup("lineObjs");
        
        this.removeElGroup("xTableLine");
        this.removeElGroup("yTableLine");
        this.removeElGroup("xText");
        this.removeElGroup("yText");
    }else{
        for(var i=0,len = this.pointObjs.length;i<len;i++){
            for(var j=0;j<this.pointObjs[i].length;j++)
                this.pointObjs[i][j].style.display='none';
        }
        
        this.hideElGroup("lineObjs");

        this.hideElGroup("xTableLine");
        this.hideElGroup("yTableLine");
        this.hideElGroup("xText");
        this.hideElGroup("yText");
    }
};


// create Point
VMLCurve.prototype.createPoint = function(sLeft,sTop,sText){
	//根据圆点的坐标,得到左上方点的坐标
	var xLeft  = sLeft - this.PointRadius;
	var xTop   = sTop  - this.PointRadius;
	var tempOval = document.createElement("<v:oval style=\"POSITION:absolute;Z-INDEX:12;LEFT:"+xLeft+"px;TOP:"+xTop+"px;width:"+2*this.PointRadius+";height:"+2*this.PointRadius+";cursor:hand;\" stroked=\"f\" fillcolor=\""+this.PointColor+"\" strokeweight=\"1px\" title='"+sText+"'/>");
	this.group.insertBefore(tempOval);
	var _index = this.pointObjs.length-1;
	
	this.pointObjs[_index].push(tempOval);
}

//以两点为坐标画线
VMLCurve.prototype.createCurveLine = function(){
	var tempLine = document.createElement("<v:PolyLine Points=\""+ this.Points +"\" style=\"Z-INDEX:11;POSITION:absolute;\" strokeweight=\""+this.LineSize+"px\" filled=\"f\" />");
	var newStroke = document.createElement("<v:stroke dashstyle='solid' color='"+this.LineColor+"'/>");
	this.group.insertBefore(tempLine);
	tempLine.insertBefore(newStroke);
	
	if(this.LineSize==0) tempLine.style.display="none";
	this.lineObjs.push(tempLine);
}



/*********************************
* 字符串转换为数字(""-->0)as_type--str,num
* 参数说明:
as_str--转换的字符串
ai_digit--转换的小数位数(null--不限制小数位数,0--转换为整型,>0按小数位数转换)
as_type--转换后返回的类型(null,"num"--转换为数字类型,"str"--转换为字符串
(按小数格式化后的字符串)
* 例如:
* str2float("10.2124568795")返回float类型10.2124568795
* str2float("10.6",0)返回Int类型11(使用四舍五入的方法)
* str2float("10.2",2)返回float类型10.1
* str2float("10.2",2,"str")返回String类型"10.20"(按小数位数格式化字符串)
* str2float("10.216",2)返回float类型10.22
* str2float("10.216",2,"str")返回String类型"10.22"
**********************************/
function str2Float(as_str,ai_digit,as_type)
{
   var fdb_tmp = 0;
   var fi_digit = 0;
   var fs_digit = "1";
   var fs_str = "" + as_str;
   var fs_tmp1 = "";
   var fs_tmp2 = "";
   var fi_pos = 0;
   var fi_len = 0;
   fdb_tmp = parseFloat(isNaN(parseFloat(fs_str))?0:fs_str);
   
   switch (true)
   {
	  case (ai_digit==null):       //不改变值,只转换为数字
		 fdb_tmp = fdb_tmp;
		 break;
	  case (ai_digit==0):          //取得整数
		 fdb_tmp = Math.round(fdb_tmp);
		 break;
	  case (ai_digit>0):            //按照传入的小数点位数四舍五入取值
		 for (var i=0;i<ai_digit;i++) fs_digit +="0";
		 fi_digit = parseInt(fs_digit);
		 fdb_tmp = Math.round(fdb_tmp * fi_digit) / fi_digit;
		 if (as_type=="str")
		 {
			fs_tmp1 = fdb_tmp.toString();
			fs_tmp1 +=((fs_tmp1.indexOf(".")!=-1)?"":".") + fs_digit.substr(1);
			fi_pos = fs_tmp1.indexOf(".") + 1 + ai_digit;
			fdb_tmp = fs_tmp1.substr(0,fi_pos);
		 }
		break;
   }
   return fdb_tmp;
} 
﻿

Sail.widget.ext.polyLine = Sail.extend(Sail.widget.ext.form,{
    legend        : true,
    legendWidth   : 100,
    defaultHeight : 250,
    lineGroup     : [],

    lineConfig    : [],
    
    //===================================================================================
    //方法 ： some func for size
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setHeight : function(h){
        Sail.widget.ext.polyLine.superclass.setHeight.call(this,h);
        this.vmlObj = this.createVMLObj({
            legend : this.legend
        });
    },
    
    setWidth : function(w){
        Sail.widget.ext.polyLine.superclass.setWidth.call(this,w);
        this.vmlObj = this.createVMLObj({
            legend : this.legend
        });
    },

    setSize : function(w,h){
        Sail.widget.ext.polyLine.superclass.setSize.call(this,w,h);
        this.vmlObj = this.createVMLObj({
            legend : this.legend
        });
    },
    
    getIntendingHeight : function(){
        return this.defaultHeight;
    },
    //===================================================================================
    //方法 ： some func for line compute
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getCoorInfo : function(maxValue){
        var robj = {maxValue:10,yCount:5};

        var digit = this.getDigit(maxValue)-1;
        var first  = Math.floor(maxValue/Math.pow(10,digit));
        var second = Math.floor(Math.round((maxValue-first*Math.pow(10,digit))/Math.pow(10,digit-1)));
        
        var _maxValue = first*Math.pow(10,digit);

        var _a = _maxValue/10;
        var _b = second*Math.pow(10,digit-1);
        var _c = Math.round(_b/_a);
        
        if(_c<5) {
            robj.maxValue = _maxValue+_a*_c;
            robj.yCount   = 10+_c;
        }
        else{
            robj.maxValue = (first+1)*Math.pow(10,digit);
            robj.yCount   = 10;
        }
        //debugger;
        
        
        return robj;
    },
    
    getMaxYScale : function(maxValue){
        
        if(this.yScaleMaxValue!=undefined && this.yScaleCount!=undefined)
            return {maxValue:this.yScaleMaxValue,yCount:this.yScaleCount};

        maxValue = (maxValue<0)?-1*maxValue:maxValue;
        if(maxValue==0) return maxValue;
        
        if(maxValue<1 && maxValue>=0){
            var digit = this.getDigitNeg(maxValue)-1;
            var v = Math.pow(10,-digit);
            var robj = {maxValue:1,yCount:5};
            return robj;
        }
        
        var digit = this.getDigit(maxValue)-1;
        var robj = {maxValue:10,yCount:5};
        
        if(digit==0){
            robj.maxValue = (maxValue>5)?10:5;
            robj.yCount   = (maxValue>5)?10:5;
            return robj;
        }else if(digit==1){
            robj.maxValue = (maxValue>50)?100:50;
            robj.yCount   = (maxValue>50)?10:5;
            return robj;
        }
        else
            return this.getCoorInfo(maxValue);
        
    },
    
    getDigitNeg : function(number){
        var count = 0;
        var tmp = number;
        
        while(tmp<1){
            tmp = tmp*10;
            count++
        }
        return count;
    },
    
    getDigit: function(number){
        var _tmp = parseInt(number,10);
        return (""+_tmp).length;
    },
    increaseArray : function(dataArray){
        var len = dataArray.length;
        
        var returnArray = new Array(len);
        returnArray[0] = parseFloat(dataArray[0]);
        
        for(var i=1;i<len;i++){
            var count = 0;
            for(var j=0;j<=i;j++){
                count +=parseFloat(dataArray[j]);
            }
            returnArray[i] = count;
        }
        
        return returnArray;
    },
    
    clear : function(){
        this.lineGroup = [];
        
        if(this.legendDiv!=undefined)
            this.legendDiv.innerHTML="";
            
        this.vmlObj.hidePolyLine(true);
    },
    
    //===================================================================================
    //方法 ： some func for load
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createLine : function(config){
        var indexs = [];

        //-------------------------------------------------------------------------------
        //处理入参 找到要赋予数据的lineConfig
        //-------------------------------------------------------------------------------
        if(config.getUrl != undefined){
            for(var i=0;i<this.lineConfig.length;i++){
                if(this.lineConfig[i].url == config.getUrl){
                    indexs.push(i);
                }
            }
        }else{
            if(config.lineIndex!=undefined){
                indexs.push(config.lineIndex);
            }else{
                Ext.Msg.alert("信息：","创建线图失败！createLine 没有找到要赋予数据的线图！");
                return;            
            }
        }

        if(indexs.length==0){
            Ext.Msg.alert("信息：","创建线图失败！createLine 没有找到要赋予数据的线图！");
            return;            
        }

        //-------------------------------------------------------------------------------
        //赋值
        //-------------------------------------------------------------------------------
        for(var i=0;i<indexs.length;i++){
            this.lineConfig[indexs[i]].jsonData = {};
            Sail.apply2(this.lineConfig[indexs[i]].jsonData,config.getData);
            
            this.dealWithJSONData(indexs[i]);
        }
        getData = null;
        
        this.createLineByConfig();
    },
    
    createXScale : function(configIndex){
        var config    = this.lineConfig[configIndex];
        config.xScale = {};
        config.xScale.xScaleText = [];
        
        //-------------------------------------------------------------------------------
        if(config.xScaleConfig==undefined){         //未定义，缺省为全月模式
            config.xScaleConfig = {type:"Date",byMonth:true};
        }

        var xScaleConfig = config.xScaleConfig;

        //debugger;
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(xScaleConfig.type=="Date"){              //X刻度类别：日期
            if(xScaleConfig.byMonth===true){        //全月(1-31)
                for(var i=0;i<31;i++){
                    config.xScale.xScaleText.push(i+1);
                }
            }else{
                if(xScaleConfig.beginDate!=undefined && xScaleConfig.endDate!=undefined){
                    config.xScale.xScaleText = sys_getdatelistbetween(xScaleConfig.beginDate,xScaleConfig.endDate);
                    
                    var reader   = config.reader;
                    var lineData = Sail.getSubObj(config.jsonData,reader.root);         //取得点数据集合
                    lineData = (lineData instanceof Array)?lineData:[lineData];         //有值，转换为数组        

                    var xField   = reader.xCoordinate;
                    var yField   = reader.yCoordinate;
                    
                    var validIndex = -1;
                    
                    for(var i=0;i<lineData.length;i++){
                        var tmpObj = lineData[i];           //取得一个数据定义对象（可能包含多线）
                        var _x = tmpObj[xField];
                        var _y = tmpObj[yField];
                        
                        if(_y == undefined) {
                            continue;
                        }
                        validIndex++;
                        for(var j=0;j<config.xScale.xScaleText.length;j++){
                            if(config.xScale.xScaleText[j]==_x){
                                config.store.xValue[validIndex] = j+1;
                            }
                        }
                    }
                    
                    for(var k=0;k<config.xScale.xScaleText.length;k++){
                        var item = config.xScale.xScaleText[k];
                        config.xScale.xScaleText[k] = item.split("-")[2];
                    }
                }else{
                    for(var i=0;i<31;i++){
                        config.xScale.xScaleText.push(i+1);
                    }
                }
            }
            //debugger;
        }else if(xScaleConfig.type=="Data"){
            //debugger;
            var reader   = config.reader;
            var lineData = Sail.getSubObj(config.jsonData,reader.root);         //取得点数据集合
            lineData = (lineData instanceof Array)?lineData:[lineData];         //有值，转换为数组        
            
            var xField   = reader.xCoordinate;
            
            for(var i=0;i<lineData.length;i++){
                var tmpObj = lineData[i];           //取得一个数据定义对象（可能包含多线）
                var _x = tmpObj[xField];
                
                if(xScaleConfig.initXScale!=undefined && typeof xScaleConfig.initXScale == "function"){
                    var v = xScaleConfig.initXScale(_x,tmpObj)||"";
                    config.xScale.xScaleText.push(v);
                }else{
                    config.xScale.xScaleText.push(config.store.xValue[i]);
                }
                config.store.xValue[i] = i+1;
            }
        }
        
    },
    
    dealWithJSONData : function(configIndex){
        //debugger;
        var config = this.lineConfig[configIndex];
        var reader = config.reader;
        
        var xField = reader.xCoordinate;
        var yField = reader.yCoordinate;
        
        //-------------------------------------------------------------------------------
        var lineData = Sail.getSubObj(config.jsonData,reader.root);         //取得点数据集合
        if(lineData==null ||lineData==undefined) return false;              //无值，返回
        lineData = (lineData instanceof Array)?lineData:[lineData];         //有值，转换为数组        

        //-------------------------------------------------------------------------------
        //从DATA中根据配置的字段，解析各个坐标值
        //-------------------------------------------------------------------------------
        config.store = {};
        config.store.xValue = [];
        config.store.yValue = [];
        config.store.titles = [];

        for(var i=0;i<lineData.length;i++){     //遍历数据集合（点集合）
            var tmpObj = lineData[i];           //取得一个数据定义对象（可能包含多线）
            
            var _x = tmpObj[xField];
            if(reader.xConversion!=undefined && typeof reader.xConversion =="function"){
                _x = reader.xConversion(tmpObj[xField]);
            }

            var _y = tmpObj[yField];
            
            if(_x !=undefined && _y!=undefined){
                var _title = "（"+tmpObj[xField]+"，"+tmpObj[yField]+"）";
                if(config.titleRender!=undefined && typeof config.titleRender == "function"){
                    _title = config.titleRender(tmpObj[xField],tmpObj[yField]);
                }

                config.store.xValue.push(_x);
                config.store.yValue.push(_y);
                config.store.titles.push(_title);
            }
        }
        
        //-------------------------------------------------------------------------------
        //如果Y轴数据是递增模式，则重计算Y坐标值和title
        //-------------------------------------------------------------------------------
        if(config.reader.yCoordinateMode!=="noIncrease"){
            config.store.yValue = this.increaseArray(config.store.yValue);

            config.store.titles = [];
            var count = config.store.yValue.length;
            for(var i=0;i<count;i++){
                var tmpObj = lineData[i];
                var _title = "（"+tmpObj[xField]+"，"+tmpObj[yField]+"）";
                if(config.titleRender!=undefined && typeof config.titleRender == "function"){
                    var tmpValue = Sail.formatNum(config.store.yValue[i]);
                    _title = config.titleRender(tmpObj[xField],tmpValue);
                }
                config.store.titles.push(_title);
            }
        }

        //-------------------------------------------------------------------------------
        //根据实际数据计算Y坐标最大值，并均分Y轴刻度
        //-------------------------------------------------------------------------------
        config.yScale = {};
        config.yScale.yScaleText  = [];

        var maxValue     = config.store.yValue.max();           //取得最大的Y坐标值
        var maxYScaleObj = this.getMaxYScale(maxValue);         //计算Y轴刻度最大值

        config.yScale.maxYScale   = maxYScaleObj.maxValue;      //Y轴最大刻度值
        config.yScale.yScaleCount = maxYScaleObj.yCount;        //Y轴刻度数

        var step = config.yScale.maxYScale/config.yScale.yScaleCount;
        for(var i=0;i<config.yScale.yScaleCount;i++){           //计算Y坐标轴刻度
            config.yScale.yScaleText.push(step+i*step);
        }
        
        //-------------------------------------------------------------------------------
        //创建X轴刻度
        //-------------------------------------------------------------------------------
        this.createXScale(configIndex);
        
        //-------------------------------------------------------------------------------
        //判断是否有折线已经存在，并且最大Y轴刻度大于当前Y轴刻度
        //-------------------------------------------------------------------------------
        var _index = -1;
        var _max   = config.yScale.maxYScale;
        for(var i =0 ;i<this.lineConfig.length;i++){
            if(this.lineConfig[i].yScale){
                if(this.lineConfig[i].yScale.maxYScale>_max){
                    _max = this.lineConfig[i].yScale.maxYScale;
                    _index = i;
                }
            }
        }

        var maxIndex = (_index!=-1)?_index:configIndex;
        var group    = this.lineConfig;
         
        for(var i =0 ;i<this.lineConfig.length;i++){
            if(this.lineConfig[i].yScale){

                group[i].yScale.maxYScale   = group[maxIndex].yScale.maxYScale;
                group[i].yScale.yScaleCount = group[maxIndex].yScale.yScaleCount;
                group[i].yScale.yScaleText  = [].concat(group[maxIndex].yScale.yScaleText);

            }
        }
    },
    
    createLineByConfig : function(){
        
        var validIndex = -1;
        var errorIndex = [];
        for(var i=0;i<this.lineConfig.length;i++){
            if(this.lineConfig[i].xScale!=undefined && this.lineConfig[i].xScale!=undefined){
                validIndex = i;
            }else{
                errorIndex.push(i);
            }
        }
        
        if(validIndex==-1){
            return;
        }
        
        var cFirst = this.lineConfig[validIndex];
        
        //--------------------------------------------------------------------------------
        if(this.legendDiv!=undefined) this.legendDiv.innerHTML="";
        this.vmlObj.hidePolyLine(true);
        this.vmlObj.hideCoordinate(true);

        //--------------------------------------------------------------------------------
        this.vmlObj.configYPerValue = cFirst.yScale.maxYScale/cFirst.yScale.yScaleCount;
        this.vmlObj.configYMinValue = this.vmlObj.configYPerValue; 

    	this.vmlObj.configXValue = cFirst.xScale.xScaleText;
        this.vmlObj.configYValue = cFirst.yScale.yScaleText;
        
        //debugger;
        //this.vmlObj.xScaleHeight = 100;
        
        //--------------------------------------------------------------------------------
        //测算X轴刻度最大长度
        //--------------------------------------------------------------------------------
        var tmpLen = [];
        for(var i=0;i<this.vmlObj.configXValue.length;i++){
            var len = Sail.getLabelWidth(this.vmlObj.configXValue[i]);
            tmpLen.push(len);
        }
        var maxLen = tmpLen.max();
        
        //--------------------------------------------------------------------------------
        //测算X轴刻度最大长度
        //--------------------------------------------------------------------------------
    	
    	var vo = this.vmlObj;
    	var configXLen	  	= vo.gpWidth - vo.configYLeft*2+20;	// 定义 X轴长度
    	var configXNum		= vo.configXValue.length;		    // X轴刻度数
    	var configXPerLen	= str2Float((configXLen-20)/configXNum,2); //定义 X轴每刻度长度
        
        if(configXPerLen<11){
            vo.xScaleHeight = 50;
            vo.xScaleTextDirection = "none";
        }else{
            if(maxLen>configXPerLen){
                vo.xScaleTextDirection = "italic";
                vo.xScaleHeight = 100;
            }else{
                vo.xScaleTextDirection = "h";
                vo.xScaleHeight = 50;
            }
        }
        
        this.vmlObj.reInit();
        
        //--------------------------------------------------------------------------------
        for(var i=0;i<this.lineConfig.length;i++){
            if(this.lineConfig[i].store){
                this.drawLine(i);
            }
        }
    },
    
    findLineIndexByName : function(name){
        this.lineConfig = this.lineConfig ||[];
        
        var ro = -1;
        for(var i=0;i<this.lineConfig.length;i++){
            if(this.lineConfig[i].name==name)
                return i;
        }
        
        return ro;
    },
    
    checkLineConfig : function(config){
        var result = {flag:true,msg:[]};

        if(config.name==undefined){
            result.msg.push("没有找到线图的名称！");
            result.flag = false;
        }

        var reader = config.reader;
        if(reader==undefined){
            result.msg.push("没有找到关于数据解析对象的定义！无法解析数据！");
            result.flag = false;
        }

        if(config.url==undefined || config.url=="") {
            result.msg.push("线图"+(config.name?"【"+config.name+"】":"")+" 没有找到关于数据源的定义！无法获取数据！");
            result.flag = false;
        }
        
        var linename = "线图【"+config.name+"】";
        var type = reader.type;
        if(type==undefined){
            result.msg.push(linename+"没有定义数据读取类型！");
            result.flag = false;
        }

        if(reader.type=="JsonReader"){
            var xCoordinate = reader.xCoordinate;
            if(xCoordinate==undefined){
                result.msg.push(linename+"没有定义 X坐标 取值字段！");
                result.flag = false;
            }
    
            var yCoordinate = reader.yCoordinate;
            if(yCoordinate==undefined){
                result.msg.push(linename+"没有定义 Y坐标 取值字段！");
                result.flag = false;
            }else{
                if(config.name instanceof Array){
                    if(reader.yCoordinate instanceof Array){
                        if(config.name.length!=reader.yCoordinate.length){
                            result.msg.push(linename+" name定义数组 与 Y坐标取值字段定义数组 长度不匹配！");
                            result.flag = false;
                        }
                    }else{
                        result.msg.push(linename+" name定义 与 Y坐标取值字段定义 类型不匹配！<br><br>应同为数组或同为字符串！");
                        result.flag = false;
                    }
                }else{
                    if(reader.yCoordinate instanceof Array){
                        result.msg.push(linename+" name定义 与 Y坐标取值字段定义 类型不匹配！<br><br>应同为数组或同为字符串！");
                        result.flag = false;
                    }
                }
            }
    
            var root = reader.root;
            if(root==undefined){
                result.msg.push(linename+"没有定义 数据对象的root！");
                result.flag = false;
            }
        }

        result.msg = result.msg.join("<br>");
        return result;
    },
    
    load : function(){
        
        //-------------------------------------------------------------------------------
        //判断参数完整性
        //-------------------------------------------------------------------------------
        if(arguments.length!=1 || (typeof arguments[0] !="object")){
            Ext.Msg.alert("信息：","参数传递错误！");
            return;
        }

        var config = arguments[0];
        
        var result = this.checkLineConfig(config);
        if(result.flag==false){
            Ext.Msg.alert("信息：",result.msg);
            return;
        }
        
        //-------------------------------------------------------------------------------
        //处理默认值
        //-------------------------------------------------------------------------------
        config.name =(config.name instanceof Array)?config.name:[config.name];
        var reader = config.reader;
        reader.yCoordinate =(reader.yCoordinate instanceof Array)?reader.yCoordinate:[reader.yCoordinate];
        
        //-------------------------------------------------------------------------------
        //处理入参(update or add to lineConfig)
        //-------------------------------------------------------------------------------
        for(var i=0;i<config.name.length;i++){
            var lc  = {};
            Sail.apply2(lc,config);
            
            lc.name = lc.name[i];
            lc.reader.yCoordinate = lc.reader.yCoordinate[i];
            
            if(lc.lineConfig instanceof Array){
                lc.lineConfig = lc.lineConfig[i];
            }
            
            if(lc.titleRender instanceof Array){
                lc.titleRender = lc.titleRender[i];
            }

            var index = this.findLineIndexByName(lc.name);
            if(index==-1){
                this.lineConfig.push(lc);
            }else{
                this.lineConfig = this.lineConfig.replace(index,lc);    //对象数组替换
            }
        }
        
        //-------------------------------------------------------------------------------
        //读取数据
        //-------------------------------------------------------------------------------
        var theObj = this;
        var getUrl = config.url;
        
        this.ownerFrame.showLoadMask('加载数据，请稍后......');
        
        Sail.postData(config.url,{},function(flag,getData){
            theObj.ownerFrame.loadMask.hide();
            theObj.createLine.call(theObj,{
                getData: getData,
                getUrl : getUrl
            });
        },function(){
            theObj.ownerFrame.loadMask.hide();
            Ext.Msg.alert("信息：","读取数据失败...");
            
        });
    },
    
    reload : function(newconfig){

        //-------------------------------------------------------------------------------
        //效验入参
        //-------------------------------------------------------------------------------
        if(newconfig.name==undefined){
            Ext.Msg.alert("信息：","重载时，没有指定线图的名称！");
            return;
        }

        if(newconfig.url==undefined){
            Ext.Msg.alert("信息：","重载时，没有指定线图新的数据源！");
            return;
        }

        //-------------------------------------------------------------------------------
        //寻找指定的线条
        //-------------------------------------------------------------------------------
        var index = this.findLineIndexByName(newconfig.name);
        if(index==-1){
            Ext.Msg.alert("信息：","重载时，没有指定名称【"+newconfig.name+"】的线图！");
            return;
        }else{
            var lc = {};
            Sail.apply2(lc,this.lineConfig[index]);
            Sail.apply2(lc,newconfig);
            
            this.load(lc);
        }
    },
    
    add2CheckList: function(listconfig){
        //debugger;
        if(this.legendDiv==undefined) return;
        
        var html = "";
        html+="<table >";
        html+="<tr height=6><td colspan=2></td></tr>";
        html+="<tr><td colspan=3 style='font:normal 12px verdana;font-weight:bold;color:#15428B'>图例:</td></tr>";
        html+="<tr height=6><td colspan=2></td></tr>";
        
        var lineIndex=-1;
        for(var i=0;i<this.lineConfig.length;i++){
            var disabled = false;
            if(this.lineConfig[i].xScale==undefined || this.lineConfig[i].xScale==undefined){
                disabled = true;
            }else{
                lineIndex++;
            }

            var tmpId  = this.id+"_line_"+lineIndex;
            var _color = this.lineConfig[i].lineConfig.lineColor||"#FF6600";
            var _name  = this.lineConfig[i].name;
            if(disabled)
                html+="<tr height=16><td width=20><input id='"+tmpId+"' type=checkbox disabled checked></td>";
            else
                html+="<tr height=16><td width=20><input id='"+tmpId+"' type=checkbox checked></td>";
                
            html+="<td width=16 style='background-color:"+_color+"'>&nbsp;</td>";
            html+="<td nowrap style='font:normal 12px verdana;'>"+_name+"</td></tr>";
            html+="<tr height=6><td colspan=2></td></tr>";
        }
        html+="</table>";
        this.legendDiv.innerHTML = html;
        
        var left = this.width-((this.legendWidth==undefined)?120:this.legendWidth)-10;
        this.legendDiv.style.left = left;
        (function(){   
            var lineIndex=-1;
            for(var i=0;i<this.lineConfig.length;i++){
                if(this.lineConfig[i].xScale!=undefined && this.lineConfig[i].xScale!=undefined){
                    lineIndex++;
                }

                Ext.get(this.id+"_line_"+lineIndex).on('click',function(e){
                    
                    var index = parseInt(e.target.id.replace(this.id+"_line_",""));
                    var check = e.target.checked;
                    
                    var line = this.vmlObj.lineObjs[index];
                    if(check){
                        if(line) {
                            if(this.lineConfig[index].lineConfig.lineSize===0)
                                line.style.display='none';
                            else
                                line.style.display='';
                        }
                        
                        var points = this.vmlObj.pointObjs[index];
                        for(var i=0;i<points.length;i++)
                            points[i].style.display='';
                    }else{
                        if(line) line.style.display='none';
                        var points = this.vmlObj.pointObjs[index];
                        for(var i=0;i<points.length;i++)
                            points[i].style.display='none';
                    }
                },this);
            }
        }).defer(50,this);
        
    },
    
    drawLine : function(configIndex){
        
        var config = this.lineConfig[configIndex];
        
        lineConfiger = config.lineConfig||{};
        
        //--------------------------------------------------------------------------------
        var pointRadius = (lineConfiger.pointRadius!=undefined)?lineConfiger.pointRadius:3;           //点直径
    	var lineSize    = (lineConfiger.lineSize!=undefined)?   lineConfiger.lineSize:1;              //线的大小
    	var pointColor  = (lineConfiger.pointColor!=undefined)? lineConfiger.pointColor:"#FF6600";    //点的颜色
    	var lineColor   = (lineConfiger.lineColor!=undefined)?  lineConfiger.lineColor:"#FF6600";     //线的颜色
        
        var xCoordinate = config.store.xValue;
        var yCoordinate = config.store.yValue;
        var titles      = config.store.titles;
        //debugger;
        //for(var i=0;i<yCoordinate.length;i++){
        //    yCoordinate[i] = yCoordinate[i]*50;
        //}
        //--------------------------------------------------------------------------------
    	this.vmlObj.setPointsProp(pointRadius,lineSize,pointColor,lineColor);   //设置圆点的属性
    	
        //--------------------------------------------------------------------------------
    	this.vmlObj.setPointsValue(xCoordinate,yCoordinate,titles);	            //画线

        this.add2CheckList();
    	
    },
            
    //===================================================================================
    //方法 ： some func for VML 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createVMLObj : function(config){
        //xScaleHeight
        //-----------------------------------------------------------
        //-----------------------------------------------------------
        var gpWidth = this.width-4;
        
        //-----------------------------------------------------------
        //-----------------------------------------------------------
        var createFlag = (this.vmlObj ==undefined)?false:true;
        var vc = (this.vmlObj ==undefined)?new VMLCurve({
            objDiv:this.children[0].el,
            parentName:this.name,
            showText:this.showText
        }):this.vmlObj;

        vc.needOriginValue = false;
    	vc.gpWidth = gpWidth;
    	vc.gpHeight = this.height-((this.showTitle==true)?26:0)-20;
    	vc.graphType = "polyLine";      //20090917
    	
    	vc.configXValue = [];       //X轴坐标值文本
        vc.configYValue = [];       //
        vc.configXHeight = 3;
    	vc.init();
        
        if(createFlag){
            this.createLineByConfig();
        }
            
    	return vc;        
    },    

    createLegend : function(){
        this.legendText="线图";
        //if(this.legend!==true){
        if(this.legend===true){
            var legendDiv = document.createElement( "DIV" );        //创建标题容器
            this.children[0].el.appendChild(legendDiv);                    //添加到包裹容器

            var legendConfig = {
                left:this.width-((this.legendWidth==undefined)?120:this.legendWidth)-10,
                top:4,
                width : (this.legendWidth==undefined)?120:this.legendWidth,
                height:this.height-21,
                cursor:"default",
                position:"absolute",
                border : "0px solid #ff0000"
            };
            Sail.apply(legendDiv.style,legendConfig);
            
            this.legendDiv = legendDiv;
            
        }
    },
    
    //===================================================================================
    //方法 ： some func for after create widget 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    afterCreateWidget : function(){
        //debugger;
        this.createLegend();
        //this.createMsg();
        
        this.vmlObj = this.createVMLObj({
            legend : this.legend
        });
    },

    //===================================================================================
    //===================================================================================
    lastFunc : function(){
    }
});


Sail.widget.ext.histogram = Sail.extend(Sail.widget.ext.form,{
    legend        : true,
    legendWidth   : 100,
    defaultHeight : 250,
    
    histogramConfig : {
        lspace  : 30,
        rspace  : 30,
        mspace  : 10,
        width   : 30
    },
    
    legendColor   : ['#758FB2','#6DB04C','#838383'],
    dataMode      : "remote",
    autoFill      : true,
    
    //===================================================================================
    //方法 ： reset height、width or size  
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setHeight : function(h){
        Sail.widget.ext.histogram.superclass.setHeight.call(this,h);
        this.refresh();
    },
    
    setWidth : function(w){
        Sail.widget.ext.histogram.superclass.setWidth.call(this,w);
        this.refresh();
    },

    setSize : function(w,h){
        Sail.widget.ext.histogram.superclass.setSize.call(this,w,h);
        this.refresh();
    },
    
    getIntendingHeight : function(){
        return this.defaultHeight;
    },



//    setHeight : function(h,mode){
//        //debugger;
//        this.height = h;
//        this.container.setHeight(h);
//        this.adjustHeight();
//
//        if(mode!==false){ this.refresh(); }
//    },
//    setWidth : function(w,mode){
//        //debugger;
//        this.width = w;
//        this.container.setWidth(w);
//        this.adjustWidth();
//
//        if(mode!==false){ this.refresh(); }
//    },
//    
//    setSize : function(w,h){
//        //debugger;
//        this.setWidth(w,false);
//        this.setHeight(h,false);
//        
//        this.refresh();
//    },
    
    refresh : function(){
        //debugger;
        if(this.vmlConfig==undefined){
            return;
        }else{
            //this.clear();
            this.vmlObj.hideHistogramCoordinate(true);
            this.children[0].el.scrollLeft = 0;
            this.render(true);
        }
    },

    clear : function(){
        this.vmlObj.hideHistograms(true);
    },

    hideHistograms : function(){
        this.vmlObj.hideHistograms(false);
    },
    
    //===================================================================================
    //方法 ： load data 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    load : function(){
        var a = arguments;
        
        //-------------------------------------------------------------------------------
        //判断参数完整性
        //-------------------------------------------------------------------------------
        if(a.length!=1 || (typeof a[0] !="object" && typeof a[0]!='string')){
            Ext.Msg.alert("信息：","参数传递错误！");
            return;
        }

        var config = (typeof a[0]=='string')?{url:a[0]}:a[0];
        
        this.url = config.url||this.url;
        if(this.url==undefined || this.url==""){
            Ext.Msg.alert("信息：","没有找到获取数据的服务名称！");
            return;
        }
        
        this.reader = config.reader || this.reader;
        if(this.reader==undefined || (typeof this.reader!="object")){
            Ext.Msg.alert("信息：","没有定义或错误的数据解析对象！");
            return;
        }

        this.legendText = config.legendText || this.legendText;
        
        this.titleRender = config.titleRender || this.titleRender;
        
        //-------------------------------------------------------------------------------
        //加载数据
        //-------------------------------------------------------------------------------
        var theObj = this;
        
        this.ownerFrame.showLoadMask('加载数据，请稍后......');
        
        if(this.dataMode==="remote"){
            Sail.postData(this.url,{},function(flag,getData){
                if(flag){
                    theObj.jsonData = getData;
                    theObj.renderHistogram();
                    theObj.ownerFrame.loadMask.hide();
                }else{
                    theObj.ownerFrame.loadMask.hide();
                    Ext.Msg.alert("信息：",getData.dataset.response.content);
                }
            },function(){
                theObj.ownerFrame.loadMask.hide();
                Ext.Msg.alert("信息：","读取数据失败...");
                
            });
        }
    },

    //===================================================================================
    //方法 ： dealWith json data
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getMaxYCoordinate : function(maxValue2){
        if(maxValue2==0) return maxValue2;

        var maxValue = maxValue2/0.9;
        //debugger;
        var perValue = maxValue/10;
        perValue = parseInt((""+perValue).split(".")[0],10);
        
        var digit = this.getDigit(perValue)-1;
        var tmpPV = perValue/Math.pow(10,digit);
        
        perValue = (Math.round(tmpPV)+1)*Math.pow(10,digit);
        
        robj = {};
        robj.maxValue = perValue*10;
        robj.yCount   = 10;
        return robj;

        var digit = this.getDigit(maxValue)-1;
        var robj = {maxValue:10,yCount:5};
        
        if(digit==0){
            robj.maxValue = (maxValue>5)?10:5;
            robj.yCount   = (maxValue>5)?10:5;
            return robj;
        }
        
        var tmpMax1 = maxValue/Math.pow(10,digit);
        
        
        var tmpMax2 = Math.round(tmpMax1);
        
        tmpMax2 = (tmpMax2>tmpMax1)?tmpMax2:tmpMax2+1;
        robj.maxValue = ((tmpMax2>5)?10:5)*Math.pow(10,digit);
        robj.yCount   = 10;

        return robj;
    },
    getNearNum : function(maxvalue,limit){
        return (maxvalue>limit*0.5)?limit:this.getNearNum(maxvalue,limit*0.5);
    },
    getDigit: function(number){
        var _tmp = parseInt(number,10);
        return (""+_tmp).length;
    },
        
    dealWithJsonData : function(){
        
        //-------------------------------------------------------------------------------
        //必要的定义完整性的效验
        //-------------------------------------------------------------------------------
        if(this.jsonData == undefined) return false;
        if(this.reader == undefined || typeof this.reader !='object') return false;
        if(typeof this.reader.root !='string')  return false;
        if(typeof this.reader.xCoordinate !='string')  return false;
        if(this.reader.yCoordinate == undefined )  return false;
        this.reader.yCoordinate = (this.reader.yCoordinate instanceof Array)?this.reader.yCoordinate:[this.reader.yCoordinate];

        //-------------------------------------------------------------------------------
        //提取数据，并转换为数组形式
        //-------------------------------------------------------------------------------
        var hData = Sail.getSubObj(this.jsonData,this.reader.root);
        
        if(hData==null ||hData==undefined) {return false;}
        hData = (hData instanceof Array)?hData:[hData];
        
        //-------------------------------------------------------------------------------
        //存在剔除函数定义，则提出符合条件的数据
        //-------------------------------------------------------------------------------
        if(this.reader.spliceFunc!=undefined && typeof(this.reader.spliceFunc)=='function'){
            for(var i=hData.length-1;i>=0;i--){
                if(this.reader.spliceFunc(hData[i]))
                    hData.splice(i,1);
            }
        }

        //-------------------------------------------------------------------------------
        //从jsonDat中根据reader抽取相关数据，组成histogramConfig结构
        //-------------------------------------------------------------------------------
        this.vmlConfig = {
            store  : {  xValues:[],     yValues:[],  titles:[] },
            xScale : {  text:[] },
            yScale : {  text:[] }
        };
        
        var vc = this.vmlConfig;
        var tmpYValue = [];
        
        //-------------------------------------------------------------------------------
        //提取X轴刻度文本，各个数据点的X、Y坐标，标题文本
        //-------------------------------------------------------------------------------
        for(var i=0;i<hData.length;i++){
            vc.xScale.text.push(hData[i][this.reader.xCoordinate]||"");

            vc.store.xValues.push(i+1);
            vc.store.yValues.push([]);
            vc.store.titles.push([]);
            
            var xField = this.reader.xCoordinate;
            var yField = this.reader.yCoordinate;
            
            for(var j=0,len=yField.length;j<len;j++){
                
                var v = hData[i][yField[j]]||0;
                vc.store.yValues[i].push(v);

                tmpYValue.push(v);
            
                var _title = "（"+hData[i][xField]+"，"+v+"）";
                if(this.titleRender!=undefined && typeof this.titleRender == "function"){
                    _title = this.titleRender(hData[i][xField],v,yField[j]);
                }
                vc.store.titles[i].push(_title);
            }
        }
        
        //-------------------------------------------------------------------------------
        //计算Y轴刻度文本
        //-------------------------------------------------------------------------------
        var maxValue = eval("Math.max("+tmpYValue.join(',')+")");
        var cdObject = this.getMaxYCoordinate(maxValue);
        var maxY     = cdObject.maxValue;
        var count    = cdObject.yCount;
        for(var i=0;i<count;i++){ vc.yScale.text.push(maxY/count+i*(maxY/count)); }

        vc.yScale.maxValue = maxY;
        vc.yScale.count    = count;
        vc.yScale.yPerValue= maxY/count;
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        return true;
    },
    
    computeVMLSize : function(){
        var vmlObj = this.vmlObj;
        
    	vmlObj.gpHeight = this.height-((this.showTitle==true)?26:0)-20;

        //-------------------------------------------------------------------------------
        //测算X轴长度及VML宽度
        //-------------------------------------------------------------------------------
        var hc    = this.histogramConfig;
        var count = this.reader.yCoordinate.length;
        var perW  = hc.lspace+hc.width*count+hc.mspace*(count-1)+hc.rspace;
        
        var gpWidth = this.width-4;
        var tmpW = this.vmlConfig.xScale.text.length*perW;
        
        if(tmpW>gpWidth){
            if(this.autoFill===true){
                vmlObj.gpWidth=gpWidth;
            }else{
                vmlObj.gpWidth=(tmpW>gpWidth)?tmpW:gpWidth;
    	        vmlObj.gpHeight = vmlObj.gpHeight-20;

                var bodyHeight = this.height-((this.showTitle==true)?26:0);
                
                Ext.get(this.children[0].el).on('scroll',function(){
                    var target = arguments[1];
                    var sleft = target.scrollLeft;
                    
                    var actWidth = this.legendDiv.offsetWidth;
                    var left     = this.width-actWidth-10;
                    this.legendDiv.style.left = left+sleft;
                    
                },this);
            }
        }else{
            vmlObj.gpWidth=gpWidth;
        }
    },
    
    computeXScale  : function(){
        var vmlObj = this.vmlObj;

        var tmpLen = [];
        for(var i=0;i<vmlObj.configXValue.length;i++){
            var len = Sail.getLabelWidth(vmlObj.configXValue[i]);
            tmpLen.push(len);
        }
        var maxLen = tmpLen.max();

        //-------------------------------------------------------------------------------
    	var configXLen	  	= vmlObj.gpWidth - vmlObj.configYLeft*2+20;	// 定义 X轴长度
    	var configXNum		= vmlObj.configXValue.length;		        // X轴刻度数
    	var configXPerLen	= str2Float((configXLen-20)/configXNum,2);  //定义 X轴每刻度长度
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.autoFill===true){
            var count  = this.reader.yCoordinate.length;
            var space1 = this.space1 || 10;
            var hwidth = this.hwidth || 30;
            
            var cwidth = hwidth*count+space1*(count-1);
            if(cwidth>(configXPerLen-4)){
                hwidth = configXPerLen/(count*2+1);
            }
            if(hwidth<10) vmlObj.showText = false;
            vmlObj.hwidth = hwidth;
            vmlObj.space1 = hwidth;
        }
        //-------------------------------------------------------------------------------
        if(configXPerLen<11){
            vmlObj.xScaleHeight = 50;
            vmlObj.xScaleTextDirection = "none";
        }else{
            if(maxLen>configXPerLen){
                vmlObj.xScaleTextDirection = "italic";
                vmlObj.xScaleHeight = 100;
            }else{
                vmlObj.xScaleTextDirection = "h";
                vmlObj.xScaleHeight = 50;
            }
        }
    },
    
    //===================================================================================
    //方法 ： render 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    renderHistogram : function(){
        if(this.dealWithJsonData()){
            this.clear();
            this.children[0].el.scrollLeft = 0;
            this.render();
        }else{
            //Sail.showMsg('处理柱图数据发现异常！ ');
        }
    },
    
    render : function(){
        
        var isAdjust = arguments[0]||false;
        
        if(this.vmlObj == undefined) 
            this.vmlObj = this.createVMLObj();
        var vmlObj = this.vmlObj;
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        vmlObj.configYPerValue = this.vmlConfig.yScale.yPerValue;
        vmlObj.configYMinValue = this.vmlConfig.yScale.yPerValue; 
    	vmlObj.configXValue    = this.vmlConfig.xScale.text;
        vmlObj.configYValue    = this.vmlConfig.yScale.text;;

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.computeVMLSize();      //测算X轴长度
        this.computeXScale();       //测算X轴刻度最大长度，判定斜体/正体 显示
        vmlObj.reInit();
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var xValues = this.vmlConfig.store.xValues;
        var yValues = this.vmlConfig.store.yValues;
        var titles  = this.vmlConfig.store.titles;
        
        var date1 = new Date();
        vmlObj.createHistograms(xValues,yValues,titles,['#99BBE8','#8EE663','#ababab'],isAdjust);	
        var date2 = new Date();

        //alert("create histogram use time: "+(date2-date1));
        //-------------------------------------------------------------------------------
        this.createLegend();
    },
    
    //===================================================================================
    //方法 ： create func  
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createLegend : function(){
        var _id;
        if(this.legend===true){

            if(this.legendDiv==undefined){
                var legendDiv = document.createElement( "DIV" );            //创建标题容器
                this.children[0].el.appendChild(legendDiv);                    //添加到包裹容器
                //debugger;
                var legendConfig = {
                    left:this.width-((this.legendWidth==undefined)?120:this.legendWidth)-10,
                    top:4,
                    width : (this.legendWidth==undefined)?160:this.legendWidth,
                    zIndex : 10,
                    cursor:"default",
                    position:"absolute",
                    overflow:'hidden',
                    border : "0px solid #ff0000"
                };
                Sail.apply(legendDiv.style,legendConfig);
                
                this.legendDiv = legendDiv;
                
                _id = this.legendDiv.uniqueID+"_tl";
                this.legendDivID = _id;
            }else{
                _id = this.legendDivID;
            }

            if(this.legendText!=undefined){
                
                var colorList = this.legendColor ||['#758FB2','#6DB04C','#838383'];
                var html = "";
                html+="<table width=100% >";
                html+="<tr height=6><td colspan=2></td></tr>";
                html+="<tr id='"+_id+"'><td colspan=2 style='cursor:hand;font:normal 12px verdana;font-weight:bold;color:#15428B'><input type=checkbox checked>图例</td></tr>";
                html+="<tr height=6><td colspan=2></td></tr>";
                
                for(var i=0;i<this.legendText.length;i++){
                    html+="<tr height=16><td width=24% height=16 style='background-color:"+(colorList[i]||"#000000")+"'>&nbsp;</td>";
                    html+="<td style='padding-left:4px;font:normal 12px verdana;'>"+this.legendText[i]+"</td></tr>";
                    html+="<tr height=6><td colspan=2></td></tr>";
                }
    
                html+="</table>";
                this.legendDiv.innerHTML = html;

                var left = this.width-((this.legendWidth==undefined)?120:this.legendWidth)-10;
                this.legendDiv.style.left   = left;
                if(this.legendDivHeight==undefined)
                    this.legendDivHeight    = this.legendDiv.scrollHeight;
                    
                this.legendDivFlag          = true;
                this.legendDiv.style.height = this.legendDivHeight;

                Ext.get(_id).on('click',function(){
                    //debugger;
                    if(this.legendDivFlag){
                        this.legendDiv.style.height=33;
                        this.legendDivFlag = false;
                    }else{
                        this.legendDiv.style.height=this.legendDivHeight;
                        this.legendDivFlag = true;
                    }
                },this);

            }

        }
    },    

    createMsg : function(){
        var msgDiv = document.createElement( "DIV" );        //创建标题容器
        this.children[0].el.appendChild(msgDiv);                    //添加到包裹容器

        var msgConfig = {
            left:10,
            top:4,
            width : '90%',
            height: 21,
            zIndex : 10,
            cursor:"default",
            position:"absolute",
            textAlign:'left',
            fontWeight:'bold',
            paddingTop:2,
            color : "#ff0000",
            border : "0px solid #ff0000"
        };
        Sail.apply(msgDiv.style,msgConfig);
        
        this.msgDiv = msgDiv;
    },
    showMsg : function(msg){
        this.msgDiv.style.display='';       //屏蔽了中间文本显示层
        this.msgDiv.innerText=msg;
        
        this.msgDiv.style.left = 10+this.children[0].el.scrollLeft;
    },
    hideMsg : function(){
        this.msgDiv.style.display='none';
    },

    createVMLObj : function(config){
        
        var vc = new VMLCurve({
            objDiv      : this.children[0].el,
            parentName  : this.name,
            showText    : this.showText
        });
        
        vc.needOriginValue = false;
    	vc.gpWidth  = this.width-4;
    	vc.gpHeight = this.height-((this.showTitle==true)?26:0)-20;
    	vc.graphType= "histogram";
    	
    	vc.configXValue    = [];
        vc.configYValue    = [];
        vc.configXHeight   = 3;
        vc.configXTextMode = "middleSpace"; 
        vc.init();
        //debugger;
    	return vc;        
    },
    
    //===================================================================================
    //方法 ： create func  
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    afterCreateWidget : function(){
        this.createMsg();
        this.vmlObj = this.createVMLObj();
    }
    
});﻿
/*------------------------------------------------------------------------------------------------------\
|                                  表格类组件基类 Sail.baseGrid                                         |
|-------------------------------------------------------------------------------------------------------|
|作者：于俊杰                                                                                           |
|时间：2009-04-13 创建并注释                                                                            |
|说明：                                                                                                 |
|-------------------------------------------------------------------------------------------------------|
|             【对象】                    |                          【说明】                           |
|-------------------------------------------------------------------------------------------------------|
| Sail.widget.baseGrid                    | 对象：基类                                                  |
|                                         |                                                             |
|-------------------------------------------------------------------------------------------------------|
|                                       Copyright (c) 2009 YuJunJie                                     |
\------------------------------------------------------------------------------------------------------*/


Sail.widget.baseGrid = Sail.extend(Sail.widget,{

    //-----------------------------------------------------------------------------------
    //默认定义
    //-----------------------------------------------------------------------------------
    defaultIdField      : "id",
    defaultSysFlag      : "sysFlag",
    defaultCreatorField : "creator",
    defaultDataRoot     : "",
    defaultSortable     : true,
    
    totalProperty       : "dataset.totalRecords",
    successProperty     : "dataset.response.success",
    messageProperty     : "dataset.response.content",
    
    //-----------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------
    titleIcon   : "icon-grid",              //标题默认ICON
    showTitle   : true,                     //是否显示标题    
    border      : true,                     //是否显示边框
    collapsible : false,                    //是否允许折叠表格，默认允许
    autoFill    : true,                     //是否自动适应宽度
    
    //-----------------------------------------------------------------------------------
    //-----------------------------------------------------------------------------------
    pageSize    : 6,                        //默认的每页记录数
    dataMode    : "local",                  //数据加载模式
    url         : "",                       //数据源URL
    
    //-----------------------------------------------------------------------------------
    haveNumberCol : true,                   //是否自动创建一个序号列
    haveCheckCol  : true,                   //是否自动创建一个选择列
    singleSelect  : false,                  //如果创建选择列，选择列的选择模式（单/多选）
    
    smRowspan     : 2,                      //表格扩展标题头行数
    usePlugins    : false,                  //是否使用表格扩展
    
    //-----------------------------------------------------------------------------------
    tbar          : null,                     //标题栏按钮定义

    bbar          : true,                   //是否包含页脚翻页栏
    //bindRelation  : {},                     //表格数据绑定关系对象

    //tbarButtons   : new Array(),
    //editors       : {},
    //colStore      : new Array(),
    //colStoreConfig: [],
    //extConfig     : {},
    //cellActions   : [],
    //cellFunctions : [],
    
    //-----------------------------------------------------------------------------------
    heightConfig     : {                    //Intending height 属性
        singleHeader : 24,                  //表头高度
        titleBar     : 25,                  //标题高度
        row          : 21,                  //记录行高度
        tbar         : 26,                  //标题按钮栏高度
        bbar         : 26                   //页脚翻页栏高度
    },

    initComponent : function(){
    },
    
    setWidth : function(w){
        //debugger;
        this.width = w;
        this.container.setWidth(w);
        if(this.el!=undefined && this.el.setWidth!=undefined){
            this.el.setWidth(w);
            this.getView().refresh();
            if(this.autoFill===true){
                this.getView().fitColumns(false,true);
            }
        }
    },
    setHeight:function(h){
        //debugger;
        this.height = h;
        this.container.setHeight(h);
        if(this.el != undefined)
            this.el.setHeight(h);
    },
    
    //===================================================================================
    //方法 ： some function for get...
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getIntendingHeight:function(){          //获取表格预计高度
        //debugger;
        var ih = 0;
        ih = (this.showTitle===true)?ih + this.heightConfig.singleHeader:ih;
        
        if(this.usePlugins===false){
            ih += this.heightConfig.titleBar;
        }else{
            ih += (this.heightConfig.titleBar*this.smRowspan);
        }
            
        ih = (this.tbar!=undefined&&this.tbar!=false&&this.tbar.length>0)?ih + this.heightConfig.tbar:ih;
        ih = (this.bbar===true)?ih + this.heightConfig.bbar:ih;
        ih += this.pageSize*this.heightConfig.row;
        ih += 10;

        return ih;
    },

    getRecordDefine : function(){           //获取表格数据模型中record定义
        return this.config.recordConfig;
    },
    getReader : function(){                 //获取JSON读取对象
        return this.config.reader;
    },
    
    getFieldsFromCol : function(col){       //从列模型中抽取dataIndex，剔除重复，返回数组
        var fs = [];
        for(var i=0;i<col.length;i++){
            if(col[i]["dataIndex"]!=undefined){
                var haveFlag = fs.have(col[i]["dataIndex"]);
                if(!haveFlag) fs.push(col[i]["dataIndex"]);
            }
            if(col[i]["nameIndex"]!=undefined){
                var haveFlag = fs.have(col[i]["nameIndex"]);
                if(!haveFlag) fs.push(col[i]["nameIndex"]);
            }
        }
        return fs;
    },    
    
    isAddField : function(f,a){             //判断一个字段是否是通过field扩展定义的字段
        for(var i=0;i<a.length;i++){
            if((typeof a[i]) =="object"){
                if(a[i].name==f) return true;
            }else{
                if(a[i]==f) return true;
            }
        }
        return false;
    },

    //===================================================================================
    //方法 ： some create function for data model ...
    //参数 ： 
    //返回 :  
    //说明 ： 创建数据模型及其相关子对象
    //===================================================================================
    createRecordDefine : function(config){  //创建record的定义
        
        var _fields = this.getFieldsFromCol(config.col);
        
        if(!_fields.have(config.idField))      _fields.push(config.idField);
        if(!_fields.have(config.sysFlag))      _fields.push(config.sysFlag);
        if(!_fields.have(config.creatorField)) _fields.push(config.creatorField);
        
        var rConfig = [];
        for(var i=0;i<config.field.length;i++){
            if((typeof config.field[i]) =="object") rConfig.push(config.field[i]);
            else rConfig.push({name:config.field[i]});            
        }

        for(var i=0,len=_fields.length;i<len;i++){
            if(this.isAddField(_fields[i],config.field)){continue;}
            rConfig.push({name:_fields[i]});
        }
        
        if(config.headerroot!=undefined && config.headerroot!='')
            rConfig.push({name:config.headerroot});
            
        if(config.dataroot!=undefined && config.dataroot!='')
            rConfig.push({name:config.dataroot});
            
        return rConfig;
    },
    createRecordObj : function(config){     //根据定义，创建record对象
        return Ext.data.Record.create(config.recordConfig);
    },
    createReader : function(config){        //根据配置，创建reader对象
        return new Ext.data.JsonReader({
                root            : config.root,
                id              : config.idField,
                totalProperty   : config.totalProperty,
                successProperty : config.successProperty,
                messageProperty : config.messageProperty
            }, config.record
        );
    },
    createStore  : function(config){        //根据配置，创建store对象
        return new Ext.data.Store({
            url: config.url,
            reader: config.reader
        });
    },
    
    createDataModel : function(config){     //创建数据模型及其相关
        config.recordConfig = this.createRecordDefine(config);
        config.record       = this.createRecordObj(config);
        config.reader       = this.createReader(config);
        config.store        = this.createStore(config);
    },

    //===================================================================================
    //方法 ： createColEditor
    //参数 ： 
    //返回 :  
    //说明 ： 创建可编辑表格列编辑器
    //===================================================================================
    createColEditor : function(col,ceDefine){
        var editor = null;
        var config = {};
        var to = this;
        
        if(ceDefine.config!=undefined && ceDefine.config.regex!=undefined ){
            var a = ( typeof ceDefine.config.regex == 'object');
            //debugger;
        }
        switch (ceDefine.type){
            //-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------
            case "textField":
                Ext.apply(config,ceDefine.config);
                config.selectOnFocus = true;
                this.editors["col_"+col] = new Ext.form.TextField(config);
                break;
            //-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------
            case "comboBox":
                var store = null;
                
                var _fields = [];
                var _textField =(ceDefine.config.fieldText!=undefined)?ceDefine.config.fieldText:"text";
                var _valueField=(ceDefine.config.fieldValue!=undefined)?ceDefine.config.fieldValue:"code";
                var _root      =(ceDefine.config.root!=undefined)?ceDefine.config.root:"dataset.simplecombobox";
                _fields.push(_textField);
                _fields.push(_valueField);
                
                if(ceDefine.config.otherFields!=undefined){
                    _fields =  _fields.concat(ceDefine.config.otherFields);
                }
                
                if(ceDefine.config.url && ceDefine.config.url!=""){
                    store = new Ext.data.Store({
            	        proxy : new Ext.data.HttpProxy({url: ceDefine.config.url}),
            	        reader: new Ext.data.JsonReader({root: _root}, _fields)
                    });

                    //-----------------------------------------------------------------------------
                    //combox 加载模式判定
                    //-----------------------------------------------------------------------------
                    if(ceDefine.config.autoWidth!=undefined)
                        config.autoWidth = ceDefine.config.autoWidth;

                    if(ceDefine.config.maxHeight!=undefined)
                        config.maxHeight = ceDefine.config.maxHeight;
                    var _mode = (ceDefine.config.mode)?ceDefine.config.mode:"local";
                    if(_mode!='remote') store.load();
                }
                else
                    store = new Ext.data.SimpleStore({fields:_fields,data : []});
                
                this.colStore[col]=store;      //数据引用保存到组件属性中，按列
                this.colStoreConfig[col] = _fields;

                config ={
                    store: store,displayField:_textField,
                    //autoWidth:true,
                    //width:300,
                    //mode: 'remote',
                    autoShow : true,
                    name:_textField,
                    valueField:_valueField,
                    typeAhead: true,
                    triggerAction: 'all',
                    loadingText:"读取...",
                    emptyText:'未选择...',
                    selectOnFocus:true,
                    editable : false/*,
                    lazyInit : false    //*///日*/
                };
                
                config.mode = (ceDefine.config.mode)?ceDefine.config.mode:"local";
                this.editors["col_"+col] = new Ext.form.ComboBox(config);

                var theObj = this.editors["col_"+col];
                break;
            //-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------
            case "dateField":
                config = {format:"Y-m-d",readOnly:true,emptyText:"选择日期"};
                //config = {readOnly:true,emptyText:"选择日期"};
                Ext.apply(config,ceDefine.config);
                this.editors["col_"+col] = new Ext.form.DateField(config);
                break;
            //-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------
            case "timeField":
                Ext.apply(config,ceDefine.config);
                config.maxLength = 8;
                config.selectOnFocus = true;
                this.editors["col_"+col] = new Ext.form.timeField(config);
                break;
            //-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------
            case "numberField":
                Ext.apply(config,ceDefine.config);
                config.selectOnFocus = true;
                this.editors["col_"+col] = new Ext.form.NumberField(config);
                break;
            //-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------
            case "selectfield":
                config.allowBlank = true;
                config.blankText = "未选择...";
                config.showValue = (ceDefine.config.text)?ceDefine.config.text:"text";
                config.dataValue = (ceDefine.config.value)?ceDefine.config.value:"id";
                
                //config.readOnly  = true;
                Ext.apply(config,ceDefine.config);
                
                //debugger;
                this.editors["col_"+col] = new Ext.form.SelectField(config);
                break;
            //-------------------------------------------------------------------------------------
            //-------------------------------------------------------------------------------------
            case "selectfieldadvanced":
                
                config.allowBlank = true;
                config.blankText = "未选择...";
                config.showValue = (ceDefine.config.text)?ceDefine.config.text:"text";
                config.dataValue = (ceDefine.config.value)?ceDefine.config.value:"id";
                
                //config.readOnly  = true;
                Ext.apply(config,ceDefine.config);
                
                //debugger;
                this.editors["col_"+col] = new Ext.form.SelectFieldAdvanced(config);
                break;
            default:
                break;
        }
        
        return this.editors["col_"+col];
        
        //return editor;
    },
    
    //===================================================================================
    //方法 ： createColModel
    //参数 ： 
    //返回 :  
    //说明 ： 创建EXT的列模型
    //===================================================================================
    createColModel : function(config){      //创建表格的列模型对象
        var sm = null;
        var colModelDefine = [];
        var theObj = this;
        this.aIndex = 0;
        
        if(config.haveNumberCol===true){    //是否包含序号列       
            colModelDefine.push(new Ext.grid.RowNumberer());
            this.aIndex++;
        }
        if(config.haveCheckCol===true){     //是否包含选择列
            if(config.singleSelect) sm = new Ext.grid.RadioSelectionModel({singleSelect:true});
            else sm = new Ext.grid.CheckboxSelectionModel();
            
            if(config.smRowspan!=undefined) sm.rowspan = config.smRowspan;
            
            colModelDefine.push(sm);
            this.aIndex++;
        }
        
        this.colStore = [];
        this.colStoreConfig = [];
        this.editors = {};
        
        for(var i=0;i<this.aIndex;i++){
            this.colStore.push("");                     //列编辑器数据结构全局
            this.colStoreConfig.push("");               //列编辑器配置全局
        }
        
        var r= config;
        for(var i=0;i<r.col.length;i++){                //构造列模型

            this.colStore.push("");                     //列编辑器数据结构全局
            this.colStoreConfig.push("");               //列编辑器配置全局
            
            r.col[i]["sortable"] = (r.col[i]["sortable"]!=undefined)?r.col[i]["sortable"]:this.defaultSortable;
            r.col[i]["locked"]   = false;
            r.col[i]["id"]       = (r.col[i]["id"]==undefined)?r.col[i]['header']:r.col[i]["id"]; //列标题文本作为ID
            r.col[i]["css"]      = "border-right:1px #EDEDED solid;";    //列分隔线
            r.col[i]["align"]    =(r.col[i]["align"]!=undefined)?r.col[i]["align"]:"center";
            r.col[i]['dataIndex']= r.col[i]['dataIndex'] || config.idField;

            //---------------------------------------------------------------------------
            //---------------------------------------------------------------------------
            //debugger;
            if(r.editor[i]!=undefined){
                r.col[i]["editor"] =(this.page.isView())?{}:this.createColEditor(i+this.aIndex,r.editor[i]);
            }else{
                r.col[i]["editor"]   = {};
            }


            if(r.editor[i] && r.editor[i].config){              //20090805 add by yujunjie for ylzb
                if(r.editor[i].config.allowBlank!=undefined){
                    if(r.editor[i].config.allowBlank==false){
                        if(r.col[i]['header']!=undefined)
                            if(r.col[i]['header'].indexOf('*')==-1)
                                r.col[i]['header']="<font style='font:normal 12px verdana; color:#ff0000'>*</font>"+r.col[i]['header'];
                    }
                }
            }

            if(this.page.isAdd() || this.page.isUpdate()||this.page.isView()){  //20090730 add by yujunjie(add view)
                if(this.type=='editGrid'){
                    if(config.editor[i].type=="comboBox"){
                        var wConfig = config.editor[i].config;
                        var _textField =(wConfig.fieldText)?wConfig.fieldText:"text";
                        var _valueField=(wConfig.fieldValue)?wConfig.fieldValue:"code";
                        eval("var tf = function(value,metadate,r,rowIndex,colIndex){ \n"
                            +"  var dataIndex = (theObj.el.getColumnModel().config[colIndex].nameIndex);\n"
                            +"  if(dataIndex==undefined) return '';\n"
                            +"  var _name = r.get(dataIndex);\n"
                            +" return (_name==''||_name==undefined)?'':_name;\n"
                            +"}\n");
        
                        config.col[i]["renderer"] = tf;
                    }else if(config.editor[i].type=="dateField"){
                        eval("var formatDate = function(value){ return value ? value.dateFormat('Y-m-d') : '';}");
                        config.col[i]["renderer"] = formatDate;
                    }     
                }           
            }                
            //---------------------------------------------------------------------------
            //---------------------------------------------------------------------------
            if(r.col[i]["actionCol"]===true){           //如果是功能列

                //----------------------------------------------------------------------
                //20090730 add by yujunjie for spsc
                //----------------------------------------------------------------------
                var _hidden = true;                     
                if(r.col[i]['actionList']==undefined){
                    if(this.page.isList()){         
                        if(this.page.haveOperFun(r.col[i].header,this.title)!=false){
                            _hidden=false;
                        }
                    }
                }else{
                    for(var aindex=0;aindex<r.col[i]['actionList'].length;aindex++){
                        if(this.page.isList()){         
                            if(this.page.haveOperFun(r.col[i]['actionList'][aindex],this.title)!=false){
                                _hidden=false;
                                break;
                            }
                        }
                    }
                }
                //----------------------------------------------------------------------
                //add over
                //----------------------------------------------------------------------
                
                
                var text = r.col[i]["header"];
                eval("var tf = function(val,p,r){return \"<span class=actionSpan>"+text+"</span>\";}");
                if(r.col[i]["renderer"]==undefined){    //默认的渲染方法
                    r.col[i]["renderer"] = tf;
                }else{                                  //20090730 add by yujunjie
                    var nowColRenderer = r.col[i]["renderer"];
                    var pageObj = this.page;
                    var gridTitle = this.title;

                    var newRenderer = function(val,p,r){
                        var colHTML = nowColRenderer.call(this,val,p,r);
                        var actionTxt =(colHTML=="")?"":colHTML.split(">")[1].split("<")[0];
                        
                        return (pageObj.haveOperFun(actionTxt,gridTitle)!=false)?colHTML:"";
                    }
                    r.col[i]["renderer"] = newRenderer;
                }
                
                r.col[i]["align"]   = "center";
                r.col[i]["fixed"]   = true;
                r.col[i]["sortable"]= false;
                r.col[i]["hidden"]  = _hidden;          //20090730 add by yujunjie
            }
            colModelDefine.push(r.col[i]);
        }
        
        config.columnModel = new Ext.grid.ColumnModel(colModelDefine);

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(config.usePlugins!=undefined){
            var ta = [];
            if(config.haveNumberCol){
                ta.push({header:"", rowspan:config.smRowspan});
                if(!config.haveCheckCol){
                    config.headers[0] = ta.concat(config.headers[0]);
                }
            }
                
            if(config.haveCheckCol){
                 ta.push(sm);
                 config.headers[0] = ta.concat(config.headers[0]);
                 //this.headers[0].push(sm);
            }
            config.columnModel.headers = config.headers;
        }        
        
        return true;
    },
    
    //===================================================================================
    //方法 ： createGridConfig
    //参数 ： 
    //返回 :  
    //说明 ： 创建EXT的表格配置对象
    //===================================================================================
    createGridConfig : function(config){

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var gridConfig = {
            stripeRows:true,
            viewConfig: {autoFill:config.autoFill},
            loadMask: true,
            animCollapse:false
        };

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        gridConfig.sm     = (config.singleSelect)?new Ext.grid.RadioSelectionModel({singleSelect:true}):new Ext.grid.CheckboxSelectionModel();
        if(config.smRowspan!=undefined) gridConfig.sm.rowspan = config.smRowspan;

        gridConfig.store  = config.store;
        gridConfig.cm     = config.columnModel;
        gridConfig.border = config.border;
        gridConfig.collapsible = config.collapsible;
        
        if(config.showTitle){
            gridConfig.title   = config.title;
            gridConfig.iconCls = config.titleIcon;
        }
        //debugger;
        if(config.tbar!=undefined && (config.tbar instanceof Array) ){
            this.tbarButtons = [];
            
            var index=0;
            for(var i=0;i<this.tbar.length;i++){
                if(this.tbar[i]=="-") continue;
                
                if(typeof this.tbar[i] =='string'){
                    this.tbar[i]={text:this.tbar[i]};
                }
                
                this.tbar[i].id=this.id+index;
                index++;
                if(this.tbar[i].text=="新增") this.tbar[i].iconCls="grid_add";
                else if(this.tbar[i].text=="删除") this.tbar[i].iconCls="grid_del";
                else this.tbar[i].iconCls="grid_bt";
                this.tbarButtons.push({text:this.tbar[i].text});
                
                if(this.page.isList()){         //20090730 add by yujunjie for spsc
                    if(this.page.haveOperFun(this.tbar[i].text,this.title)==false){
                        this.tbar[i].disabled=true;
                        this.tbar[i].hidden=true;
                    }
                }
                
                if(this.page.isView()){         //20090730 add by yujunjie for 原料增补
                    this.tbar[i].hidden = true;
                }
            }
            gridConfig.tbar = this.tbar;
        }

        if(config.bbar){
	        gridConfig.bbar= new Ext.PagingToolbar({
	            widget : this,
                pageSize: (config.pageSize)?config.pageSize:6,
                store: config.store,
                beforePageText:'第',
                afterPageText:'页，共 {0}页',
                displayMsg: '显示第 {0} - {1} 条，共 {2} 条',
                emptyMsg: "没有记录",
                displayInfo: true
            })
        }

        if(config.usePlugins===true){
            ;
        }else{
            gridConfig.width    = this.width;
            gridConfig.height   = this.height;
            gridConfig.renderTo = this.getOCD();
        }
        //debugger;
        if(config.usePlugins===true){
            gridConfig.plugins= new Ext.ux.plugins.XGrid();
        }
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------

        Sail.apply(gridConfig,config.extConfig);

        this.gridConfig = gridConfig;
        return true;
        
    },
    
    //===================================================================================
    //方法 ： createSetConfig
    //参数 ： 
    //返回 :  
    //说明 ： 规范数据，创建表格配置对象
    //===================================================================================
    createSetConfig : function(){
        
        this.config = {};
        var config  = this.config;
        var br      = this.bindRelation;
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        config.totalProperty    = this.totalProperty;
        config.successProperty  = this.successProperty;
        config.messageProperty  = this.messageProperty;
        
        config.url          = this.url;
        config.singleSelect = this.singleSelect;
        config.haveNumberCol= this.haveNumberCol;
        config.haveCheckCol = this.haveCheckCol;

        config.smRowspan    = this.smRowspan; 
        config.usePlugins   = this.usePlugins; 

        config.titleIcon    = this.titleIcon;
        config.showTitle    = this.showTitle;
        config.tbar         = this.tbar;
        config.bbar         = this.bbar;
        
        config.title        = this.title;
        config.collapsible  = this.collapsible;
        config.border       = this.border;
        config.autoFill     = this.autoFill;
        config.pageSize     = this.pageSize;
        
        config.extConfig    = this.extConfig;
        
        config.smRowspan    = this.smRowspan;
        config.usePlugins   = this.usePlugins;
        
        //-------------------------------------------------------------------------------
        //从bindRelation中抽取数据
        //-------------------------------------------------------------------------------
        config.headerroot   = (br.headerroot!=undefined)?br.headerroot:"";
        config.dataroot     = (br.dataroot!=undefined)?br.dataroot:"";
        
        config.headers      = (br.headers!=undefined)?br.headers:[];

        config.root         = (br!=undefined)?br.root:this.defaultDataRoot;
        config.idField      = (br.id!=undefined)?br.id:this.defaultIdField;
        config.sysFlag      = (br.sysFlag!=undefined)?br.sysFlag:this.defaultSysFlag;
        config.creatorField = (br.creatorField!=undefined)?br.creatorField:this.defaultCreatorField;
                
        config.field        = (br.field==undefined)?[]:br.field;        //字段定义模型
        config.col          = (br.col==undefined)?[]:br.col;            //列模型
        config.editor       = (br.editor==undefined)?[]:br.editor;      //编辑器模型
        
        config.headers      = (br.headers==undefined)?[]:br.headers;    //使用EXT实现的多表头定义
        
        config.editor       = (br.editor==undefined)?[]:br.editor;
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        //config.recreate     = (config.recreate!=undefined)?config.recreate:false;
    },
    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    loadDataByConfig : function(){
        var paramsInfo = {method:"GET"};
        if(this.bbar==true){
            paramsInfo.start = 0;
            paramsInfo.limit = (this.pageSize)?this.pageSize:6;
        }
        
        var theObj = this;
        var grid = this.el;
        
        var loadConfig = {
            params:paramsInfo,
            scope : grid,
            callback :function(){
                //debugger;
                var success  = arguments[2];
                var _request = arguments[1];
                //debugger;
                if(!success){
                    if(_request.datasetFlag){
                        grid.getStore().removeAll();
                    }else{
                        Ext.Msg.show({
                            title: '系统信息',buttons: Ext.MessageBox.OK,icon: Ext.MessageBox.INFO,
                            msg: (_request.errorInfo)?_request.errorInfo:'网络异常！请刷新或检查网络！'
                        });
                    }
                }
                //theObj.selectFirstRow();                        
                theObj.afterLoad();
            }
        };
        //debugger;
        if(this.url!="" && this.url!=undefined){
            this.getStore().load(loadConfig);
        }
    },

    load : function(){
        var a = arguments;
        var _url = (a.length==0)?this.url:a[0];
        this.url = _url;
        
        var theObj = this;
        var grid = this.el;
        
	    var sm = this.el.getSelectionModel(); 
        if(sm){
            sm.deselectRange(0,this.pageSize);
        }
        
        //-----------------------------------------------------------
        //-----------------------------------------------------------
        var paramsInfo = {method:"GET"};
        if(this.bbar==true){
            paramsInfo.start = 0;
            paramsInfo.limit = (this.pageSize)?this.pageSize:6;
        }
        
        var loadConfig = {
            params:paramsInfo,
            scope : grid,
            callback :function(){
                //debugger;
                var success = arguments[2];
                var _request = arguments[1];
                grid.loadMask.el.unmask(this.removeMask);
                if(grid.getBottomToolbar())
                    grid.getBottomToolbar().loading.enable();
                var results = arguments[0];
                //debugger;
                if(!success){
                    results =[];
                    if(_request.datasetFlag){
                        grid.getStore().removeAll();
                    }else{
                        Ext.Msg.show({
                            title: '系统信息',buttons: Ext.MessageBox.OK,icon: Ext.MessageBox.INFO,
                            msg: (_request.errorInfo)?_request.errorInfo:'网络异常！请刷新或检查网络！'
                        });
                    }
                }
                theObj.afterLoad(results);
            }
        };
                
        grid.getStore().proxy = new Ext.data.HttpProxy({url:_url});
        grid.getStore().load(loadConfig);
    },    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    beforeCreateGridEl : function(){
    },
    afterCreateGridEl  : function(){
    },
    
    createGridEl : function(config){
        this.beforeCreateGridEl();
        this.el = new Ext.grid.GridPanel(config);
        //debugger;
        if(this.config.usePlugins===true){
            this.el.height=this.height;
            this.el.render(this.getOCD().id);
            this.el.reconfigure(this.el.store, this.el.getColumnModel());
        }
        
        this.afterCreateGridEl();
    },

    createGrid : function(config){
        config = config||{};
        Sail.apply(this,config);
        //-------------------------------------------------------------------------------
        this.createSetConfig();                 //搜集信息，配置 this.config 内容

        //-------------------------------------------------------------------------------
        this.createDataModel(this.config);      //创建数据模型及其相关子对象，并纳入this.config
        this.createColModel(this.config);       //根据this.config 创建列模型
        this.createGridConfig(this.config);     //根据this.config 创建表格配置对象
        //-------------------------------------------------------------------------------
        this.createGridEl(this.gridConfig);
    },

    createWidgetElement : function(){
        
        this.id = this.getOCD().id+"_grid";
        
        this.createGrid();                      //创建表格对象实体
        
        this.loadDataByConfig();
        //debugger;
    },

    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getButtonIndexByText : function(t){
        for(var i=0,len=this.tbarButtons.length;i<len;i++){
            if(this.tbarButtons[i]["text"]==t) return i;
        }
        return -1;
    },
    getButton : function(key){
        var type =  typeof key;
        if(type=="string"){
            var index = this.getButtonIndexByText(key);
            if(index==-1) {
                //alert("没有找到符合条件的按钮！");
                return null;
            }
            var id = this.id+index;
            if(this.el == undefined) return null;       //2009-08-10 add by yujunjie
            
            return this.el.getTopToolbar().items.get(id);
        }else if(type=="number"){
            key = (key==0)?0:key+1;
            return this.el.getTopToolbar().items.get(key);
        }else{
            alert("传递的参数错误！");
        }
        return null;
    },
    addButtonHandler : function(btname,handler){
        if(this.type=='dynamicGrid'){
            this.btEvents = (this.btEvents)?this.btEvents:[];
            
            this.btEvents.push({
                btname : btname,
                handler:handler
            });
            
        }else{
            var bt = this.getButton(btname);
            if(bt!=null){
                bt.on('click',handler,this);
            }
        }
    },
    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setColHidden  : function(keys,hidden){
        var ca = [];
        var cm = this.getColumnModel();
        
        if(keys instanceof Array){
            for(var i=0;i<keys.length;i++){
                if(typeof keys[i] =='string'){
                    var col = cm.getIndexById(keys[i]);
                    if(col!=-1) ca.push(col);
                }else if(typeof keys[i] == 'number'){
                    ca.push(keys[i]);
                }else{
                    continue;
                }
            }
        }else{
            if(typeof keys =='string'){
                var col = cm.getIndexById(keys);
                if(col!=-1) ca.push(col);
            }else if(typeof keys == 'number'){
                ca.push(keys);
            }else{
                return;
            }
        }
        for(var i=0;i<ca.length;i++){
            this.getColumnModel().setHidden(ca[i],hidden);
        }

        //this.el.getColumnModel().setHidden(col,hidden);
    },

    hideCols : function(keys){
        this.setColHidden(keys,true);
    },
    showCols : function(keys){
        this.setColHidden(keys,false);
    },
    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    afterLoad : function(){
        //debugger;
    },
    on : function(eventName, handler, scope, options){
        
        if(eventName=='afterload'){
            this.afterLoad = handler;
        }else if(eventName=='rowclick'){
            /*this.el.on('rowclick',function(grid,row,e){
                //processEvent : function(name, e){
                //var v = this.view;
                //findCellIndex
                //debugger;
                alert(row);
            },this);
            return;*/
            
            var theObj = this;
            var sm = this.el.getSelectionModel();
            sm.addListener("rowselect",function(_sm,_index,_r){
                //debugger;
                var id=_r.get(theObj.config.idField);
                if(id)
                    handler.call(this,id,_index,_r);
                else
                    handler.call(this,"",_index,_r);
            });
        }else if(eventName=='cellclick'){
            this.el.on('cellclick', function(g,r,c,e){
                var a = [];
                var o = {};

                var cm   = g.getColumnModel();
                o.header = (c===false)?"":cm.getColumnHeader(c);
                o.field  = (c===false)?"":cm.getDataIndex(c);
                o.record = g.getStore().getAt(r);
                o.value  = o.record.get(o.field);
                o.el     = g;

                a.push(r); a.push(c); a.push(o);
                handler.apply(this,a);
            }, this);
        }
        else{
            this.el.on(eventName, handler, scope, options);
        }
    },

    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getStore : function(){
        return this.el.getStore();
    },
    getCount : function(){
        return this.getStore().getCount();
    },
    getRecord : function(row){
        return this.getStore().getAt(row);
    },
    getColumnModel : function(){
        return this.el.getColumnModel();
    },
    getView : function(){
        return this.el.getView();
    },
    getCell : function(r,c){
        return this.getView().getCell(r,c);
    },
    getHeaderByCol   : function(col){
        return this.getColumnModel().config[col]["header"];
    },
    getColumnByHeader : function(header){
        var cm = this.getColumnModel();
        return cm.getIndexById(header);
    },
    getDataIndexByColumn : function(col){
        var cm = this.getColumnModel();
        return cm.getDataIndex(col);
    },
    getDataIndexByHeader: function(header){
        var index = this.getColumnByHeader(header);
        
        var cm = this.getColumnModel();
        return cm.getDataIndex(index);
    },

    getIDField : function(){
        if(this.config!=undefined)
            return this.config.idField||"";
        else
            return "";
    },
    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getField  : function(row,dataIndex){
        if(arguments.length==1){
            var a = [];
            var count = this.getCount();
            for(var i=0;i<count;i++){
                a.push(this.getRecord(i).get(arguments[0]));
            }
            return a;
        }else{
            return this.getRecord(row).get(dataIndex);
        }
    },
    getFieldByHeader : function(row,header){
        if(arguments.length==1){
            var dataIndex = this.getDataIndexByHeader(arguments[0]);
            return this.getField(dataIndex);
        }else{
            var dataIndex = this.getDataIndexByHeader(header);
            return this.getField(row,dataIndex);
        }
    },
    getFieldByColumn : function(row,col){
        if(arguments.length==1){
            var dataIndex = this.getDataIndexByColumn(arguments[0]);
            return this.getField(dataIndex);
        }else{
            var dataIndex = this.getDataIndexByColumn(col);
            return this.getField(row,dataIndex);
        }
    },
    getCellText : function(r,c){
        c = (typeof c =='string')?this.getColumnByHeader(c):c;
        var cell = this.getCell(r,c);
        return cell.children[0].innerText;        
    },
    
    setCellHTML : function(r,c,html){
        c = (typeof c =='string')?this.getColumnByHeader(c):c;
        var cell = this.getCell(r,c);
        cell.children[0].innerHTML = html;                
    },
    setCellText : function(r,c,text){
        c = (typeof c =='string')?this.getColumnByHeader(c):c;
        var cell = this.getCell(r,c);
        cell.children[0].innerText = text;                
    },
    setFieldValue : function(){
    },
    setTitle : function(t){
        this.el.setTitle(t);
    },    
    setHeader : function(col,header){
        var cm = this.getColumnModel();

        cm.setColumnHeader(col,header);
        cm.config[col].id = header;
    },
    setHeaders : function(beginCol,endCol,headers){
        for(var i=beginCol;i<=endCol;i++){
            this.setHeader(i,headers[i-beginCol]);
        }
    },

    setButton : function(btArray,status){
        btArray = (typeof btArray =='string')?[btArray]:btArray;
        
        for(var i=0;i<btArray.length;i++){
            var bt = this.getButton(btArray[i]);
            if(status=="disable")
                bt.disable();
            else if (status=="disable")
                bt.enable();
            else if(status=='hidden')
                bt.hide();
            else if(status=='show')
                bt.show();
            else
                ;
        }
    },

    removeAll : function(){
        this.getStore().removeAll();
    },
    remove : function(row){
        var store = this.getStore();
        store.removeByIndex(row);
        this.getView().refresh();
    },
    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    addAction : function(actionName,fn){
        this.cellActions = this.cellActions || [];
        this.cellFunctions = this.cellFunctions ||[];
        
        this.cellActions.push(actionName);
        this.cellFunctions.push(fn);
    },
    getCellFunc : function(en){
        this.cellActions = this.cellActions ||[];
        
        for(var i=0;i<this.cellActions.length;i++){
            if(this.cellActions[i]==en){
                return this.cellFunctions[i];
            }
        }
        return null;
    },

    /*addListener : function(en,fn,scope,option){
        //alert('原框架中该方法已经被 addAction 方法替代。。。');
    },*/
    
    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getSelectionModel : function(){
        return this.el.getSelectionModel();
    },
    getSelections : function(){
        var sm = this.getSelectionModel(); 
        var sa = sm.getSelections();
        var ra = [];
        if(arguments.length==0){
            for(var i=0;i<sa.length;i++){
                ra.push(sa[i]);
            }
        }
        else{
            var field = arguments[0];
            for(var i=0;i<sa.length;i++){
                ra.push(sa[i].get(field));
            }
        }

        return ra;
    },
    getLastSelected : function(){
        var sm = this.getSelectionModel();
        
        var last = sm.getLastSelected();
        if(last==undefined){
            return {get:function(){alert("没有找到被选择的记录！");return "";}};
        }else{
            return last;
        }
    },
    getLastSelectedRow : function(){
        var record = this.getLastSelected();
        return  this.getStore().indexOf(record);
    },
    
    selectRow : function(row,keepExisting){
        keepExisting = keepExisting || false;
        this.getSelectionModel().selectRow(row,keepExisting);
    },
    selectRows : function(rows,keepExisting){
        keepExisting = keepExisting || false;
        this.getSelectionModel().selectRows(rows,keepExisting);
    },
    selectRange : function(start,end,keepExisting){
        keepExisting = keepExisting || false;
        this.getSelectionModel().selectRange(start,end,keepExisting);
    },
    selectFirstRow : function(){
        this.getSelectionModel().selectFirstRow();
    },
    deselectRow : function(row){
        this.getSelectionModel().deselectRow(row);
    },
    deselectRange : function(start,end){
        this.getSelectionModel().deselectRange(start,end);
    },
    clearSelections : function(){
        this.getSelectionModel().clearSelections();
    },
    lockSelections : function(){
        this.getSelectionModel().lock();
    },
    unlockSelections : function(){
        this.getSelectionModel().unlock();
    },
    
    //===================================================================================
    //方法 ： output html for excel 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getOutPutCol : function(){
        var col = [];
        if(this.haveNumberCol===true)
            col.push({header:"序号"});
            
        for(var i=0;i<this.bindRelation.col.length;i++){
            var item = this.bindRelation.col[i];
            if(item.dataIndex!=undefined && item.actionCol==undefined){
                var o = {header:item.header,dataIndex:item.dataIndex,renderer:item.renderer};
                col.push(o);
            }
        }
        return col;
    },
    getHTML4Excel : function(store){
        var html = [];
        
        var col = this.getOutPutCol();
        
        html.push("<table border='1'>");
        html.push("<tr><td colspan="+col.length+" align='center'><b>"+this.title+"</b></td></tr>");
        html.push("<tr><td colspan="+col.length+" align='center'>&nbsp;</td></tr>");
        
        if(this.bindRelation.headers==undefined){
            html.push("<tr>");
            for(var i=0;i<col.length;i++){
                html.push("<td><b>"+col[i].header+"</b></td>");
            }
            html.push("</tr>");
        }else{
            for(var i=0;i<this.bindRelation.headers.length;i++){
                html.push("<tr>");
                for(var j=0;j<this.bindRelation.headers[i].length;j++){
                    var rowspan = this.bindRelation.headers[i][j].rowspan;
                    var colspan = this.bindRelation.headers[i][j].colspan;
                    html.push("<td colspan="+colspan+" rowspan="+rowspan+"><b>"+this.bindRelation.headers[i][j].header+"</b></td>");
                }
                html.push("</tr>");
            }
        }
                
        for(var i=0;i<this.getCount();i++){
            var record = store.getAt(i);
            
            html.push("<tr align='center'>");
            
            if(this.haveNumberCol===true)
                html.push("<td width=40>"+(i+1)+"</td>");
             
            var begin = (this.haveNumberCol===true)?1:0;                
            for(var j=begin;j<col.length;j++){
                var value = record.get(col[j].dataIndex);
                if(col[j].renderer!=undefined){
                    value = col[j].renderer.call(this,value);
                }
                html.push("<td width=120 >"+value+"</td>");
            }
            html.push("</tr>");
        }
        
        html.push("</table>");
        
        return html.join('');
        
    },
    outPut2Excel : function(fileName){
        var outputData = this.getHTML4Excel(this.getStore());
        Sail.exportExcel(outputData,this.title+".xls");

        //Sail.exportExcel_11(outputData,this.title+".xls");
        
    },
    
    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    lastFunc : function(){
    }    
    
});






/*------------------------------------------------------------------------------------------------------\
|                              基于Sail.baseGrid 扩展的组件                                             |
|-------------------------------------------------------------------------------------------------------|
|作者：于俊杰                                                                                           |
|时间：2009-04-13 创建并注释                                                                            |
|说明：                                                                                                 |
|-------------------------------------------------------------------------------------------------------|
|             【对象】                    |                          【说明】                           |
|-------------------------------------------------------------------------------------------------------|
| Sail.widget.ext.grid                    | 对象：文本输入框                                            |
| Sail.widget.ext.editGrid                | 对象：数字输入框                                            |
|                                         |                                                             |
|-------------------------------------------------------------------------------------------------------|
|                                       Copyright (c) 2009 YuJunJie                                     |
\------------------------------------------------------------------------------------------------------*/

Sail.widget.ext.grid = Sail.extend(Sail.widget.baseGrid,{
    /*getActualHeight : function(){
        return (this.el.collapsed==true)?26:this.height;
    },*/
    
    afterCreateGridEl : function(){
        this.el.addListener("cellclick",function(grid,row,column,e){
            if(column===false) return;
            var cm = grid.getColumnModel();
            var config = cm.config[column];
            //debugger;
            var nowAction = (config.actionCol===true)?this.getCellText(row,column):config['header'];
                
            var fn = this.getCellFunc(nowAction);
            if(fn==null || fn==undefined) return;
            
            var ds = grid.getStore();
            var record = ds.getAt(row);

            var fieldName = cm.getDataIndex(column); 
            var value = record.get(fieldName);
            
            var idField = this.getIDField();
            var recordID = (idField=="")?"":record.get(idField);
            
            fn.call(e,recordID,row,record,value);
            
        },this);
        
        this.el.addListener('collapse',function(){
            //debugger;
            //this.ownerFrame.layoutC.reLayout();
        },this);
        
        this.el.addListener('expand',function(){
            //this.ownerFrame.layoutC.reLayout();
            return;
        },this);
    },
    
    onCellClick : function(col,fn){
        col = (typeof col =='number')?this.getHeaderByCol(col):col;
        this.addAction(col,fn);
    }

});


Sail.widget.ext.customCellGrid = Sail.extend(Sail.widget.ext.grid,{
    loadDataByConfig : function(){
        var paramsInfo = {method:"GET"};
        if(this.bbar==true){
            paramsInfo.start = 0;
            paramsInfo.limit = (this.pageSize)?this.pageSize:6;
        }
        
        var theObj = this;
        var grid = this.el;
        
        var loadConfig = {
            params:paramsInfo,
            scope : grid,
            callback :function(){
                //debugger;
                var success  = arguments[2];
                var _request = arguments[1];
                if(!success){
                    if(_request.datasetFlag){
                        grid.getStore().removeAll();
                    }else{
                        Ext.Msg.show({
                            title: '系统信息',buttons: Ext.MessageBox.OK,icon: Ext.MessageBox.INFO,
                            msg: (_request.errorInfo)?_request.errorInfo:'网络异常！请刷新或检查网络！'
                        });
                    }
                }else{
                    theObj.formatStoreData();                        
                }
                theObj.afterLoad();
            }
        };
        if(this.url!="" && this.url!=undefined){
            this.getStore().load(loadConfig);
        }
    },

    formatStoreData : function(){
        this.dataCopy = {};
        
        var ds = this.getStore();
        var count = ds.getCount();
        
        var header = ds.getAt(0).get(this.config.headerroot);
        var data   = ds.getAt(0).get(this.config.dataroot);
        
        this.dataCopy.header = Sail.copyObjArray(header);
        this.dataCopy.data   = Sail.copyObjArray(data);
        //this.dataCopy.count  = 5;
        
        this.getStore().removeAll();
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.bindRelation.col = [];
        for(var i=0;i<this.dataCopy.header.length;i++){
            this.bindRelation.col.push({
                "header"    : this.dataCopy.header[i]["text"],
                "dataIndex" : this.dataCopy.header[i]["field"],
                "width"     : 100
            });
        }        
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.createSetConfig();                 //搜集信息，配置 this.config 内容
        //debugger;
        this.config.recordConfig = this.createRecordDefine(this.config);
        this.config.record       = this.createRecordObj(this.config);

        this.config.reader       = new Ext.data.JsonReader({
                root            : "data",
                id              : this.config.idField,
                totalProperty   : "count"
            }, this.config.record
        );

        this.createColModel(this.config);       //根据this.config 创建列模型
        
        var newDS = new Ext.data.Store({
		    proxy: new Ext.data.PagingMemoryProxy(this.dataCopy),
		    reader: this.config.reader
        });
                
        var newCM = this.config.columnModel;
        this.el.reconfigure(newDS,newCM);
        this.el.getStore().load({params:{start:0, limit:this.pageSize}});
        
        
        if(this.autoFill===true){
            this.getView().fitColumns(true,true);
            this.getView().refresh(true);
        }
        
        this.el.getBottomToolbar().updateInfo(newDS.getCount());
    },

    load : function(){
        var a = arguments;
        var _url = (a.length==0)?this.url:a[0];
        this.url = _url;
        
        var theObj = this;
        var grid = this.el;
        
	    var sm = this.el.getSelectionModel(); 
        if(sm){
            sm.deselectRange(0,this.pageSize);
        }
        
        //-----------------------------------------------------------
        //-----------------------------------------------------------
        var paramsInfo = {method:"GET"};
        if(this.bbar==true){
            paramsInfo.start = 0;
            paramsInfo.limit = (this.pageSize)?this.pageSize:6;
        }
        
        var loadConfig = {
            params:paramsInfo,
            scope : grid,
            callback :function(){
                //debugger;
                var success = arguments[2];
                var _request = arguments[1];
                grid.loadMask.el.unmask(this.removeMask);
                if(grid.getBottomToolbar())
                    grid.getBottomToolbar().loading.enable();
                var results = arguments[0];
                //debugger;
                if(!success){
                    results =[];
                    if(_request.datasetFlag){
                        grid.getStore().removeAll();
                    }else{
                        Ext.Msg.show({
                            title: '系统信息',buttons: Ext.MessageBox.OK,icon: Ext.MessageBox.INFO,
                            msg: (_request.errorInfo)?_request.errorInfo:'网络异常！请刷新或检查网络！'
                        });
                    }
                }else{
                    theObj.formatStoreData();                        
                }
                theObj.afterLoad(results);
            }
        };
                
        grid.getStore().proxy = new Ext.data.HttpProxy({url:_url});
        grid.getStore().load(loadConfig);
    }    
});

Sail.widget.ext.ccgrid = Sail.widget.ext.customCellGrid;


Sail.widget.ext.grid2 = Sail.extend(Sail.widget.baseGrid,{

    createGridEl : function(config){
        this.beforeCreateGridEl();
        
        this.el = new Sail.widget.HTMLBaseGrid(this.config);
        
        this.afterCreateGridEl();
    },
    
    afterCreateGridEl : function(){
        this.url = "";
        //this.getOCD().style.border='1px #8DB2E3 solid';
    },
    setWidth : function(w){
        //debugger;
        this.width = w;
        this.container.setWidth(w);
        if(this.el.setWidth!=undefined){
            this.el.setWidth(w);
            this.getView().refresh();
        }
    },
    setHeight : function(h){
        
    },
    
    onCellClick : function(col,fn){
        col = (typeof col =='number')?this.getHeaderByCol(col):col;
        this.addAction(col,fn);
    }

});


Sail.widget.ext.dynamicGrid = Sail.extend(Sail.widget.baseGrid,{
    bbar : false,
    //autoFill    : false,    
    //smRowspan : 2,
    //usePlugins :true, 


    setWidth : function(w){
        //debugger;
        this.width = w;
        this.container.setWidth(w);
        if(this.el!=undefined && this.el.setWidth!=undefined){
            this.el.setWidth(w);
            this.getView().refresh();
            if(this.autoFill===true){
                this.getView().fitColumns(false,false);
            }
        }
    },
    setHeight:function(h){
        //debugger;
        this.height = h;
        this.container.setHeight(h);
        if(this.el != undefined){

            var diff = 0;
            if(this.showTitle===true) diff+=25;
            if(this.tbar!=undefined) diff+=25;
            var h2 = this.height-diff;

            this.el.originHeight = h2;
            this.el.setHeight(h);
        }
    },

    setSize: function(w,h){
        //debugger;
        this.height = h;
        this.width = w;
        
        var diff = 0;
        if(this.showTitle===true) diff+=25;
        if(this.tbar!=undefined) diff+=25;
        
        var h2 = this.height-diff;

        
        if(this.el!=undefined && this.el.setSize!=undefined){
            this.el.originHeight = h2;
            
            var ov = this.el.deferHeight;
            this.el.deferHeight = false;
            this.el.setHeight(h);
            this.el.deferHeight = ov;
            
            this.el.setWidth(w);
            this.el.height = h;
            
            this.getView().refresh();
            if(this.autoFill===true){
                this.getView().fitColumns(false,false);
            }
        }
        
        //this.setWidth(w);
        //this.setHeight(h);
    },
    
    createGrid : function(config){
        config = config||{};
        Sail.apply(this,config);
        //-------------------------------------------------------------------------------
        this.createSetConfig();                 //搜集信息，配置 this.config 内容

        //-------------------------------------------------------------------------------
        this.createDataModel(this.config);      //创建数据模型及其相关子对象，并纳入this.config
        this.createColModel(this.config);       //根据this.config 创建列模型
        this.createGridConfig(this.config);     //根据this.config 创建表格配置对象
        
        //-------------------------------------------------------------------------------
        //this.createGridEl(this.gridConfig);
    },

    createGridEl : function(config){
        //debugger;
        this.beforeCreateGridEl();
        this.el = new Ext.grid.GridPanel(config);
        //debugger;
        if(this.config.usePlugins===true){
            
            this.el.render(this.getOCD().id);
            this.el.reconfigure(this.el.store, this.el.getColumnModel());
        }
        
        this.afterCreateGridEl();
    },

    //===================================================================================
    //方法 ： some functions for get header
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    callback_Header_success : function(flag,data,source){
        source.dynamicConfig = {header:{},details:{}};
        Sail.apply(source.dynamicConfig.header,data);
        Sail.postData(source.dataUrl,{},source.callback_Detail_success,source.callback_Detail_failure,source);
    },
    callback_Header_failure : function(flag,data,source){
        Ext.Msg.alert('提示：', "获取动态表格的表头数据失败！！！      "); return true;
    },
    
    //===================================================================================
    //方法 ： some functions for get details
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    callback_Detail_success : function(flag,data,source){
        Sail.apply(source.dynamicConfig.details,data);

        var config = source.dealWithDynamicConfig();
        source.createGridByConfig(config);
    },
    callback_Detail_failure : function(flag,data,source){
        Ext.Msg.alert('提示：', "获取动态表格的列表数据失败！！！      "); return true;
    },

    load : function(){
        if(arguments.length>0){
            this.headerurl = arguments[0];
            this.dataUrl   = arguments[1];
        }
        Sail.postData(this.headerurl,{},this.callback_Header_success,this.callback_Header_failure,this);
    },

    //===================================================================================
    //方法 ： some functions
    //参数 ： void
    //返回 :  void
    //说明 ： 
    //===================================================================================
    dealWithDynamicConfig : function(){
        var headerInfo = this.dynamicConfig.header;
        var getData    = this.dynamicConfig.details;
        
        var headers = headerInfo.dataset.line;      //表头数据
        var lines   = getData.dataset.line;         //列表数据
        
        //-------------------------------------------------------------------------------
        //构造表格表头
        //-------------------------------------------------------------------------------
        var headersDefine= [];                            //定义表头数据（空结构）
        var colCount = [];
        headers =(headers instanceof Array)?headers:[headers];
        //debugger;
        
        for(var i=0;i<headers.length;i++){
            var dfs = headers[i].cell;
            var line = [];
            var count = 0;
            
            for(var j=0;j<dfs.length;j++){
                var df = dfs[j];
                var to = {style:"text-align:center;",header:df.value0}; //
                
                if(df.colspan!=undefined){
                    to.colspan=df.colspan;          //获取列合并
                    count+=parseInt(to.colspan,10);
                }
                if(df.rowspan!=undefined)
                    to.rowspan=df.rowspan;          //获取行合并
                    
                line.push(to);
            }
            colCount.push(count);
            headersDefine.push(line);        
        }
        colCount = colCount.max();                  //获得表格的列数
        
        
        if(headers.length>1){
            //debugger;
            this.smRowspan = headers.length;
            this.usePlugins =true;
        }else{
            this.smRowspan = 1;
            this.usePlugins =false;
        }
        //-------------------------------------------------------------------------------
        //构造列模型
        //-------------------------------------------------------------------------------
        var col = [];
        for(var i=0;i<colCount;i++){
            var to = {"dataIndex":"col_"+i,"css":"border-right:1px #EDEDED solid;"};
            if(headers.length==1){
                to.header = headers[0].cell[i].value0;
                to.align  = 'center';
            }
            col.push(to);
        }

        //-------------------------------------------------------------------------------
        //构造数据
        //-------------------------------------------------------------------------------
        var dataArray = [];
        //debugger;
        if(lines==undefined) lines=[];
        lines =(lines instanceof Array)?lines:[lines];
        
        for(var i=0;i<lines.length;i++){
            var line = [];              //声明一行数据的缓存区，并初始化为空
            for(var j=0;j<colCount;j++) line[j] ="";
            
            var lineData = lines[i].cell;
            for(var j=0;j<lineData.length;j++){     //遍历
                line[j] = lineData[j]["value0"]; 
            }
            
            dataArray.push(line);       //加入到数据
        }
    
        //-------------------------------------------------------------------------------
        //返回配置对象
        //-------------------------------------------------------------------------------
        return {
            'col':col,
            'dataArray':dataArray,
            'headers' : headersDefine
        };

    },
    
    createGridByConfig : function(config){
        //return;
        //debugger;
        var field     = (config.field)?config.field:[];
        var col       = (config.col)?config.col:[];
        var dataArray = (config.dataArray)?config.dataArray:[];
        var id        = (config.id)?config.id:"";
        var others    = (config.others)?config.others:{};

        this.bindRelation = this.bindRelation ||{};
        this.bindRelation.headers = config.headers;
        this.bindRelation.col     = config.col;
        
        //----------------------------------------------------------------------
        //构造record的定义
        //----------------------------------------------------------------------
        var _cm = [];
        
        if(others.colNumber){
            if(this.colNumber) {
                _cm.push(new Ext.grid.RowNumberer());
            }
        }
        if(others.colCheckbox){
            
            var sFlag = (others.colCheckbox.singleSelect)?others.colCheckbox.singleSelect:false;
            
            var sm = null;
            if(sFlag) 
                sm = new Ext.grid.RadioSelectionModel({singleSelect:true});
            else 
                sm = new Ext.grid.CheckboxSelectionModel();
            _cm.push(sm);
        }
        _cm = _cm.concat(col);
        
        //----------------------------------------------------------------------
        //构造record的定义
        //----------------------------------------------------------------------
        var _ds = []; 
        if(id!="") _ds.push(id);
        for(var i=0;i<field.length;i++){
            var oDS = {
                name: field[i], 
                type: 'string'            
            };
            _ds.push(oDS);
        }

        for(var i=0;i<col.length;i++){
            var oDS = {
                name: col[i].dataIndex,
                type: 'string'            
            };
            _ds.push(oDS);
        }
        
        //----------------------------------------------------------------------
        //绑定数据
        //----------------------------------------------------------------------
        var newDS = new Ext.data.Store({
		    proxy: new Ext.data.PagingMemoryProxy(dataArray),
		    reader: new Ext.data.ArrayReader({}, _ds)
        });
                
        var newCM = new Ext.grid.ColumnModel(_cm);
        if(config.headers!=undefined)
            newCM.headers = config.headers;

        //----------------------------------------------------------------------
        this.config.smRowspan  = this.smRowspan;
        this.config.usePlugins = this.usePlugins;
      
        this.createGridConfig(this.config);
        this.gridConfig.cm = newCM;
        this.gridConfig.store = newDS;
        
        var diff = 0;
        if(this.showTitle===true) diff+=25;
        //if(this.smRowspan>1) diff+=(this.smRowspan-1)*25;
        if(this.tbar!=undefined) diff+=25;
        
        this.gridConfig.height = this.height-diff;
        this.gridConfig.width  = this.width;
        if(this.el==undefined){
            this.el = new Ext.grid.GridPanel(this.gridConfig);
            this.el.getStore().load();
            
            if(this.config.usePlugins===true){
                this.el.render(this.getOCD().id);
                this.el.reconfigure(this.el.store, this.el.getColumnModel());
            }
            
            if(this.btEvents!=undefined){
                for(var i=0;i<this.btEvents.length;i++){
                    var btname = this.btEvents[i].btname;
                    var handler= this.btEvents[i].handler;
                    
                    var bt = this.getButton(btname);
                    if(bt!=null){
                        bt.on('click',handler,this);
                    }
                }
            }
        }

        this.el.reconfigure(newDS,newCM);
        this.el.getStore().load();
        this.el.getView().fitColumns(false,false);
        
    },

    createGridConfig : function(config){

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var gridConfig = {
            stripeRows:true,
            viewConfig: {autoFill:config.autoFill},
            loadMask: true,
            animCollapse:false
        };

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        gridConfig.sm     = (config.singleSelect)?new Ext.grid.RadioSelectionModel({singleSelect:true}):new Ext.grid.CheckboxSelectionModel();
        if(config.smRowspan!=undefined) gridConfig.sm.rowspan = config.smRowspan;

        gridConfig.store  = config.store;
        gridConfig.cm     = config.columnModel;
        gridConfig.border = config.border;
        gridConfig.collapsible = config.collapsible;
        
        if(config.showTitle){
            gridConfig.title   = config.title;
            gridConfig.iconCls = config.titleIcon;
        }
        //2009-08-10 add by yujunjie
        if(config.tbar!=undefined && (config.tbar instanceof Array) ){
            this.tbarButtons = [];
            
            var index=0;
            for(var i=0;i<this.tbar.length;i++){
                if(this.tbar[i]=="-") continue;
                
                if(typeof this.tbar[i] =='string'){
                    this.tbar[i]={text:this.tbar[i]};
                }
                
                this.tbar[i].id=this.id+index;
                index++;
                if(this.tbar[i].text=="新增") this.tbar[i].iconCls="grid_add";
                else if(this.tbar[i].text=="删除") this.tbar[i].iconCls="grid_del";
                else this.tbar[i].iconCls="grid_bt";
                this.tbarButtons.push({text:this.tbar[i].text});
                
                if(this.page.isList()){         //20090730 add by yujunjie for spsc
                    if(this.page.haveOperFun(this.tbar[i].text,this.title)==false){
                        this.tbar[i].disabled=true;
                        this.tbar[i].hidden=true;
                    }
                }
                
                if(this.page.isView()){         //20090730 add by yujunjie for 原料增补
                    this.tbar[i].hidden = true;
                }
            }
            gridConfig.tbar = this.tbar;
        }
        
        if(config.usePlugins===true){
            ;
        }else{
            gridConfig.width    = this.width;
            gridConfig.height   = this.height;
            gridConfig.renderTo = this.getOCD();
        }
        //debugger;
        if(config.usePlugins===true){
            gridConfig.plugins= new Ext.ux.plugins.XGrid();
        }
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        Sail.apply(gridConfig,config.extConfig);

        this.gridConfig = gridConfig;
        return true;
    },
    
    createWidgetElement : function(){
        this.id = this.getOCD().id+"_grid";
      
        this.createGrid();                      //创建表格对象实体
        
        if(this.headerurl!=undefined && this.headerurl!="")
            this.load();
        //debugger;
    },
    
    lastFunc : function(){
    }
});﻿
/*------------------------------------------------------------------------------------------------------\
|                                  ext可编辑表格 Sail.editGrid                                          |
|-------------------------------------------------------------------------------------------------------|
|作者：于俊杰                                                                                           |
|时间：2009-04-23 创建并注释                                                                            |
|说明：                                                                                                 |
|-------------------------------------------------------------------------------------------------------|
|             【对象】                    |                          【说明】                           |
|-------------------------------------------------------------------------------------------------------|
| Sail.widget.editGrid                    | 对象：可编辑表格                                            |
|                                         |                                                             |
|-------------------------------------------------------------------------------------------------------|
|                                       Copyright (c) 2009 YuJunJie                                     |
\------------------------------------------------------------------------------------------------------*/

Sail.widget.ext.editGrid = Sail.extend(Sail.widget.baseGrid,{
    enableBindData : true,
    //===================================================================================
    //属性 ： extConfig
    //说明 ： 
    //===================================================================================
    extConfig :{
        border:true,
        autoScroll:true,
        clicksToEdit:true,
        enableColumnMove:false,
        enableColumnResize:true,
        enableDragDrop:false,
        animCollapse:false
    },
    useDefautlFuncForadd : true,
    useDefautlFuncFordel : true,
    defaultSortable      : false,
    
    
    //===================================================================================
    //方法 ： overwrite some func for checkData
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    checkData : function(){
        var flag   = this.checkBlank();
        if(this.checkBlank()==false){
            return this.getCheckErrorMsg();
        }else{
            return this.checkColumnData();
        }
    },
    
    checkBlank : function(){
        if(this.allowBlank===false){
            if(this.getCount()==0) return false;
        }
        return true;
    },
    
    checkColumnData : function(){
        var _grid   = this;
        //debugger;
        var col     = _grid.bindRelation.col;
        var editor  = _grid.bindRelation.editor;
        var msgList = [];
        
        var cmConfig = _grid.el.getColumnModel().config;
        var beginIndex = 0;
        if(_grid.colNumber) beginIndex++;
        if(_grid.colCheckbox) beginIndex++;
                
        for(var i=0;i<_grid.getCount();i++){
            var record = _grid.el.getStore().getAt(i);
            for(var j=0;j<col.length;j++){
                if(editor[j].config !=undefined){
                    if(cmConfig[j+beginIndex].hidden) continue;
                    
                    var dataIndex  = col[j].dataIndex;
                    var allowBlank = editor[j].config.allowBlank;
                    if(allowBlank===false){
                        var _value = record.get(dataIndex);
                        if(_value==undefined || _value.toString()==''){
                            var header = col[j].header.replace('*','');
                            //var msg = "<font color=#ff0000>"+header+"</font>值不允许为空！";
                            
                            var formatInfo = "不能为空。";
                            
                            var msg = "<font color=#ff0000>"+header+"</font>值不允许为空！";
                            var msgTr = [];
                            msgTr.push("<tr style='font:normal 12px verdana;'>");
                            msgTr.push("<td>&nbsp;</td>");
                            msgTr.push("<td nowrap>&nbsp;第<font color=#ff0000>"+(i+1)+"</font>行 <font color=#ff0000>"+header+"</font></td>");
                            msgTr.push("<td style='color:#ff0000'>该数据要求：<font color=black>"+formatInfo+"</td>");
                            
                            msgTr.push("</tr>");
                                                        
                            msgList.push(msgTr.join(''));
                        }
                    }
                }
            }
        }

        if(msgList.length>0){
            var _title = ((this.title==undefined || this.title=="")?this.name:this.title);

            var ra = [];
            ra.push("<tr height=10><td colspan=3></td></tr>")
            ra.push("<tr style='font:normal 12px verdana;'>");
            ra.push("<td align=right nowrap style='color:#ff0000'>"+_title+"</td>");
            ra.push("<td>&nbsp;数据效验错误！&nbsp;&nbsp;</td>");
            ra.push("<td style='color:#ff0000'>&nbsp;</td>");
            ra.push("</tr>");
            
            ra = ra.concat(msgList);
            return ra.join('');
        }else
            return "";
                
    },
    
    //===================================================================================
    //方法 ： createGridEl
    //参数 ： 
    //返回 :  
    //说明 ： 创建可编辑表格列编辑器
    //===================================================================================
    haveField : function(name,fields){
        for(var i=0;i<fields.length;i++){
            var item = fields[i];
            if(typeof item =='object'){
                if(item.name==name) return true;
            }else{
                if(item==name) return true;
            }
        }
        return false;
    },
    createRecordDefine : function(config){  //创建record的定义
        
        var _fields = this.getFieldsFromCol(config.col);
        
        if(!_fields.have(config.idField))      _fields.push(config.idField);
        if(!_fields.have(config.creatorField)) _fields.push(config.creatorField);
        
        if(!_fields.have(config.sysFlag)&& !this.haveField(config.sysFlag,config.field)){
            config.field.push({name:config.sysFlag,type:'string',defaultValue:"1"});
        }      
        
        var rConfig = [];
        for(var i=0;i<config.field.length;i++){
            if((typeof config.field[i]) =="object") rConfig.push(config.field[i]);
            else rConfig.push({name:config.field[i],type:'string',defaultValue:""});            
        }

        for(var i=0,len=_fields.length;i<len;i++){
            if(this.isAddField(_fields[i],config.field)){continue;}
            rConfig.push({name:_fields[i]});
        }
        
        return rConfig;
    },

    createGridEl : function(config){
        this.beforeCreateGridEl();
        this.el = new Ext.grid.EditorGridPanel(config);
        if(this.config.usePlugins===true){
            this.el.height=this.height;
            this.el.render(this.getOCD().id);
            this.el.reconfigure(this.el.store, this.el.getColumnModel());
        }
        
        this.afterCreateGridEl();
    },
    loadDataByConfig : function(){
    },
    
    afterCreateGridEl : function(){
        this.addEvent2Grid();
    },
    
    addEvent2Grid : function(){
        var theObj = this;
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var bt = this.getButton("新增");
        if(this.useDefautlFuncForadd&&bt!=null){
            bt.on('click',this.addRecordByButton,this);
        }
        //debugger;
        var bt = this.getButton("删除");
        if(this.useDefautlFuncFordel&&bt!=null){                
            if(this.delMode===true){
                bt.on('click',this.delRecordByButtonPhysical,this);
            }else{
                bt.on('click',this.delRecordByButtonNormal,this);
            }
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.el.on("beforeedit",this.onBeforeEdit,this);

        this.el.on("afteredit",this.onAfterEdit,this);        
    },

    onBeforeEdit : function(o){
        //debugger;
        if(this.page.isView()){
            return false;
        }
        
        this.nowEditInfo = {};
        this.nowEditInfo.record   = o.record;
        this.nowEditInfo.field    = o.field;
        this.nowEditInfo.value    = o.value;
        this.nowEditInfo.oldValue = o.originalValue;
        this.nowEditInfo.row      = o.row;
        this.nowEditInfo.column   = o.column;
        
        
        //----------------------------------------------------------------------------
        //----------------------------------------------------------------------------
        var editor = this.editors["col_"+o.column];
        if(editor && editor.getXType()=='selectfield'){
            //debugger;
            var cm = o.grid.colModel;                   //取得列模型
            var colConfig = cm.config[o.column];        //取得当前列定义

            var dataIndex = colConfig["dataIndex"]||"";
            var idIndex   = colConfig["idIndex"]||"";
            var valueIndex= colConfig["valueIndex"]||"";
            
            var data = o.record.get(dataIndex)||"";
            var id   = o.record.get(idIndex)||"";
            var value= o.record.get(valueIndex)||"";
            
            var _data = {};
            _data[editor.idField]    = id;
            _data[editor.textField]  = data;
            _data[editor.valueField] = value;

            editor.setDataObj(_data);
            //debugger;
        }
        
        //----------------------------------------------------------------------------
        //----------------------------------------------------------------------------
        return this.lockRowBeforeEdit();
    },
    
    lockRowBeforeEdit : function(){
        return true;
    },
    
    delChangedCls : function(){
        this.bindData(this.ownerFrame.businessData);
    },
    
    checkDifferent : function(o){
        
        var cm = this.getColumnModel();
        var md = cm.config[o.column].mustDifferent;
        var di = cm.config[o.column].dataIndex;
        var row= o.row;
        var nv = o.value;
        
        if(md===true){
            var store = this.getStore();
            var count = store.getCount();
            
            for(var i=0;i<count;i++){
                if(i!=row){
                    var v = store.getAt(i).get(di);
                    if(v==nv){
                        return true;
                    }
                }
            }
        }
        return false;
    },
    
    onAfterEdit  : function(o){
        //debugger;
        /*if(this.checkDifferent(o)){
            alert('find same data...');
        }*/
        this.ownerFrame.setDataChanged(true);
        this.ownerFrame.addChangedItem(this); 

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var cm = o.grid.colModel;                   //取得列模型
        var idValue = "";                           //如果是selectField，取绑定的id字段    
        var codeValue = "";                         //如果是selectField，取绑定的code字段    
        
        var colConfig = cm.config[o.column];        //取得当前列定义
        
        var dataObj   = Sail.getSubObj(this.ownerFrame.businessData,this.config.root);   //取子对象
        var actRow    = this.getActualRow(dataObj,o.row);
        var dataIndex = cm.getDataIndex(o.column);  //取当前列 dataIndex
        var dataValue = o.record.get(dataIndex);    //取值

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(colConfig.idIndex){                      //是否包含ID绑定字段
            idValue = cm.getCellEditor(o.column,o.row).field.getIDValue();
            var _record = o.grid.store.getAt(o.row);
            _record.data[cm.config[o.column].idIndex] = idValue;
        }

        if(colConfig.valueIndex){                      //是否包含ID绑定字段
            codeValue = cm.getCellEditor(o.column,o.row).field.getCodeValue();
            var _record = o.grid.store.getAt(o.row);
            _record.data[cm.config[o.column].valueIndex] = codeValue;
        }

        
        if(colConfig.nameIndex){                    //是否包含 combox name 绑定字段
            nameValue = cm.getCellEditor(o.column,o.row).field.el.dom.value;
            var _record = o.grid.store.getAt(o.row);
            _record.set(cm.config[o.column].nameIndex,nameValue);
            
            this.ownerFrame.setBusinessData(dataObj,actRow,colConfig.nameIndex,nameValue);
        }
        
        if(colConfig.idIndex){                      //如果存在ID绑定字段(selectfield)
            this.ownerFrame.setBusinessData(dataObj,actRow,colConfig.idIndex,idValue);  //保存到数据结构
        }

        if(colConfig.valueIndex){                      //如果存在code绑定字段(selectfield)
            this.ownerFrame.setBusinessData(dataObj,actRow,colConfig.valueIndex,codeValue);  //保存到数据结构
        }

        if(cm.getCellEditor(o.column,o.row).field.getXType()=="datefield"){
            var copyDate = dataValue.clone();
            var strDate  = copyDate.format('Ymd');
            this.ownerFrame.setBusinessData(dataObj,actRow,dataIndex,strDate);    //保存到数据结构
        }
        else
            this.ownerFrame.setBusinessData(dataObj,actRow,dataIndex,dataValue);    //保存到数据结构
        
    },
    
    //===================================================================================
    //方法 ： add、 del Record func
    //参数 ： 
    //返回 :  
    //说明 ： 创建、删除记录相关方法
    //===================================================================================
    bindData : function(businessData){
        //debugger;
        if(businessData==undefined){
            businessData = this.ownerFrame.businessData;
        }
        
        //-------------------------------------------------------------------------------
        //update or view 单记录转换为数组，并调用方法绑定到表格
        //-------------------------------------------------------------------------------
        var da = Sail.getSubObj(businessData,this.config.root);
        if(da==undefined || da==null){
            //alert("【错误信息】绑定数据时，在业务数据中，没有找到指定的数据："+this.config.root);
            return;
        }
        //debugger;
        da = (da instanceof Array)?da:[da];
        
        this.bindDataByArray(this.config,da);
    },
    
    bindDataByArray : function(config,dataArray){
        var newData = [];
        //-------------------------------------------------------------------------------
        //从 dataArray 中抽取数据，组合成二维数组
        //-------------------------------------------------------------------------------
        var fieldConfig = this.createRecordDefine(config);
        for(var i=0;i<dataArray.length;i++){
            newData[i]=[];
            for(var j=0;j<fieldConfig.length;j++){ 
                newData[i][j] = dataArray[i][fieldConfig[j]["name"]]||""; 
            }
        }
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var newStore = new Ext.data.Store({     
	        proxy: new Ext.data.PagingMemoryProxy(newData),         //数据
	        reader: new Ext.data.ArrayReader({}, fieldConfig)       //行对象定义
        });
        
        //-----------------------------------------------------------------
        //-----------------------------------------------------------------
        var theGrid = this.el;
        theGrid.reconfigure(newStore,theGrid.getColumnModel());
        theGrid.getStore().load();
    },
    
    //===================================================================================
    //方法 ： add Record func
    //参数 ： 
    //返回 :  
    //说明 ： 创建记录相关方法
    //===================================================================================
    addRecordByButton : function(){
        var rd = this.config.recordConfig;
        var cd = {};
        for(var i=0;i<rd.length;i++){
            if(rd[i].type=="date"){
                cd[rd[i].name] = new Date();
            }else{
                cd[rd[i].name] = (rd[i].defaultValue)?rd[i].defaultValue:"";
            }
        }
        var p = new this.config.record(cd);
        this.addRecord(p);
    },
    addRecord2BusinessData : function(p){
        //-------------------------------------------------------------------------------
        //传值传引用啊...
        //-------------------------------------------------------------------------------
        var o2business = {};
        Sail.apply(o2business,p.data);
        for(var pr in o2business){
            if(typeof o2business[pr] =='object' && pr!='toJSONString'){
                if(o2business[pr] instanceof Date){
    	            var copyDate = o2business[pr].clone();
  	                var strDate = copyDate.format('Ymd');
	                o2business[pr] = strDate;
              	}
            }
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var bd      = this.ownerFrame.businessData;     //取得业务数据
        var tmpA    = this.config.root.split(".");      //
        var rField  = tmpA.pop();                       //获得列表位置
        var droot   = Sail.getSubObj(bd,tmpA);          //获得父位置
        var results = droot[rField];                    //获得列表

        if(results instanceof Array){
            results.push(o2business);
        }else{
            if(results==undefined || this.page.isAdd()){
                droot[rField] = new Array();
                droot[rField].push(o2business);
            }else{
                var tmpObj = {};
                Sail.apply(tmpObj,results);

                droot[rField] = new Array();
                droot[rField].push(tmpObj);
                droot[rField].push(o2business);
            }
        }
    },
    
    addRecord : function(p){
        var _index = this.el.store.getCount();
        
        this.addRecord2BusinessData(p);
        
        this.el.stopEditing();
        this.el.store.insert(_index, p);
        this.el.startEditing(_index, 0);
    },
    
    createRecord : function(){
        var rd = this.config.recordConfig;
        var cd = {};
        for(var i=0;i<rd.length;i++){
            if(rd[i].type=="date"){
                cd[rd[i].name] = new Date();
            }else{
                cd[rd[i].name] = (rd[i].defaultValue)?rd[i].defaultValue:"";
            }
        }
        var p = new this.config.record(cd);
        
        return p;
    },
    
    inFieldMap : function(map,fieldName){
        if(map==undefined) return "";
        
        for(var i=0;i<map.fieldmap.length;i++){
            var df = map.fieldmap[i].split("=");
            if(df[0]==fieldName) return df[1];
        }
        return "";
    },
    insertRecords : function(infos,map){
        if(infos==undefined || infos.items==undefined) return;
        
        var fieldmap  = (map==undefined)?((infos.map==undefined)?null:infos.map):map;
        //debugger;
        for(var i=0;i<infos.items.length;i++){
            var item = infos.items[i];
            var record = this.createRecord();
            record.editing = true;

            for(var j=0;j<this.config.recordConfig.length;j++){
                var fieldDefine = this.config.recordConfig[j];
                var fieldName = fieldDefine.name;
                
                var mapName = this.inFieldMap(fieldmap,fieldName);
                fieldName = (mapName=="")?fieldName:mapName;
                
                var value = item[fieldName]||((fieldDefine.defaultValue==undefined)?"":fieldDefine.defaultValue);
                
                if(fieldDefine.type=='date') {
                    value = (value=='')?new Date():Sail.toDate(value);
                }
                record.set(fieldDefine.name,value);
            }
            record.editing = false;
            this.addRecord(record);
        }
    },
    
    //===================================================================================
    //方法 ： del Record func
    //参数 ： 
    //返回 :  
    //说明 ： 删除记录相关方法
    //===================================================================================
    getActualRow : function(root,row){
        var _sysFlag = this.config.sysFlag;
        if(root.length){
            var index = 0;
            for(var i=0;i<root.length;i++){
                if(root[i][_sysFlag]!=undefined){
                    if(root[i][_sysFlag].toString()=='1'){
                        if(index==row) return i;
                        index++;
                    }
                }
            }
        }
        return row;
    },

    delRecordByButtonPhysical : function(){     //databusiness 物理删除
        this.delRecords(true,true);
    },
    delRecordByButtonNormal : function(){       //databusiness 标记删除
        this.delRecords(true,false);
    },
    
    delRecords : function(showMsg,delMode){
        //-------------------------------------------------------------------------------
        //提示信息
        //-------------------------------------------------------------------------------
        var sdata = this.el.getSelections();
        
        if(showMsg==true){
            if(sdata.length>0){
                if(!confirm('真的要删除所选择的数据吗？')){
                    return;
                }
            }else{
                Ext.Msg.alert("提示：","请先选择记录，再进行删除操作！");
                return;
            }
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var _idField= this.config.idField;
        var _sysFlag= this.config.sysFlag;

        var bd      = this.ownerFrame.businessData;     //取得业务数据
        var tmpA    = this.config.root.split(".");      //
        var rField  = tmpA.pop();                       //获得列表位置
        var droot   = Sail.getSubObj(bd,tmpA);          //获得父位置
        var results = droot[rField];                    //获得列表

        this.el.stopEditing();        

        //-------------------------------------------------------------------------------
        //选择删除时，先获取被删除的记录序号，然后倒序排序
        //删除记录时，按照倒序进行删除
        //-------------------------------------------------------------------------------
        var delIndex = [];
        for(var i=0;i<sdata.length;i++){
            var index = this.getStore().data.indexOf(sdata[i]);
            delIndex.push(index);
        }
        delIndex = delIndex.sort(function(a,b){
            return (a>b)?-1:1;
        });
        //debugger;
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var len = sdata.length-1;
        for(var i=0;i<delIndex.length;i++){
            var index = this.getActualRow(results,delIndex[i]);

            var idFieldValue = this.getStore().getAt(delIndex[i]).get(_idField);
            try{
                if(idFieldValue==""){
                    if(results instanceof Array){
                        results.splice(index,1);
                    }else{
                        droot[results]=[];
                    }
                }else{
                    if(results instanceof Array){
                        if(delMode===true){
                            results.splice(index,1);
                        }else{
                            results[index][_sysFlag]="0";
                        }
                    }else{
                        if(delMode===true){
                            droot[rField]=new Array();
                        }else{
                            results[_sysFlag]="0";
                        }
                    }
                }
            }catch(e){
                alert("删除记录时发生异常！");
            }
        }

        for(var i=0;i<sdata.length;i++){
            this.el.store.remove(sdata[i]);
        }

        this.el.startEditing(0, 0);
        this.el.getView().refresh();
        
    },

    removeAll : function(showMsg){
        this.el.getSelectionModel().selectAll();
        this.delRecords(showMsg,this.delMode);
    },

    //===================================================================================
    //方法 ： some func for col event
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    onBeforeEdit4Column : function(column,o,fn){
        if(o.column!=column) return;
        fn.apply(this,[column,o]);
    },
    
    addListener2Editor : function(col,ename,fn){
        if(this.page.isView()) return;

        var column = (typeof col =='string')?this.getColumnByHeader(col):col;
        var ed     = this.editors["col_"+column];
        var edtype = ed.getXType();
        var theObj = this;
        
        if(ename=='beforeedit'){
            //debugger;
            this.el.on('beforeedit',function(o){this.onBeforeEdit4Column(column,o,fn);},this);
            return;
        }
        
        if(ename=='afteredit'){
            //debugger;
            this.el.on('afteredit',function(o){this.onBeforeEdit4Column(column,o,fn);},this);
            return;
        }
                        
        switch (edtype){
            case "textfield":
                if(ename=="change"){
                    ed.addListener(ename,function(field,newValue,oldValue){
                        fn.call("",newValue,oldValue,theObj.nowEditInfo,field);
                    });
                }
                break;

            case "numberfield":
                if(ename=="change"){
                    ed.addListener(ename,function(field,newValue,oldValue){
                        fn.call("",newValue,oldValue,theObj.nowEditInfo,field);
                    });
                }else if(ename=="blur"){
                    ed.addListener(ename,function(field){
                        fn.call("",field.getValue(),theObj.nowEditInfo,field);
                    });
                }
                break;
            case "datefield" :
                if(ename=="change"){
                    ed.addListener(ename,function(field,newValue,oldValue){
                        newValue = newValue.format('Ymd');
                        oldValue = oldValue.format('Ymd');
                        fn.call("",newValue,oldValue,theObj.nowEditInfo,field);
                    });
                }
                break;
            case "timeField" :
                if(ename=="change"){
                    ed.addListener(ename,function(field,newValue,oldValue){
                        //newValue = newValue.format('Ymd');
                        //oldValue = oldValue.format('Ymd');
                        fn.call("",newValue,oldValue,theObj.nowEditInfo,field);
                    });
                }
                break;
            case "combo":
                if(ename=="select"){
                    ed.addListener(ename,function(e,r,i){
                        var text     = r.get(ed.displayField);
                        var value    = r.get(ed.valueField);
                        var oldValue = this.nowEditInfo.record.get(this.nowEditInfo.field);
                        fn.call(this,text,value,oldValue,theObj.nowEditInfo,r);
                    },this);
                }
                if(ename=="change"){
                    ed.addListener(ename,function(field,newValue,oldValue){
                        fn.call(this,newValue,oldValue,theObj.nowEditInfo,field);
                    },this);
                }
                if(ename=='beforeselect'){
                    ed.addListener(ename,function(field,record,index){
                        return fn.call(this,record,index,field);
                    },this);
                }
                break;

            default : break;
        }
        
    },

    changeEditor : function(column,config){
        if(this.page.isView()) return;
        
        var c = this.editors["col_"+column],_fields = [];
        var editType = c.getXType();

        switch (editType){
            case "combo":
                //if(xtype=="combo")      this.setFieldValue(column,0,"");
                //if(this.getCount()>0)   this.setFieldValue(column,0,"");        
                
                var _url = config.url;
                var _root       = (config.root)?config.root:"dataset.simplecombobox";
                var _textField  = (config.fieldText)?config.fieldText:"text";
                var _valueField = (config.fieldValue)?config.fieldValue:"code";
                
                _fields.push(_textField);
                _fields.push(_valueField);
                    
                //c.store.removeAll();
                c.store.proxy= new Ext.data.HttpProxy({url: _url, method: 'POST'});
        	    c.store.reader= new Ext.data.JsonReader({root: _root}, _fields);
                
                c.valueField   = _valueField;        
                c.displayField = _textField;      

                if(config.value!=undefined) c.setValue(config.value);

                c.store.load();
                this.colStore[column] = c.store;
                break;
            default : break;
        }
    },
    
    getEditor : function(col,row){
        return this.el.getColumnModel().getCellEditor(col,row).field;
    },
    
    clearCombox : function(){
        //debugger;
        if(this.page.isView()) return;
        
        var col,disMode;
        if(arguments.length==0){
            return;
        }else if(arguments.length==1){
            col = arguments[0];
            disMode=false;
        }else {
            col = arguments[0];
            disMode=arguments[1];
        }
        
        var col = (typeof col =='string')?this.getColumnByHeader(col):col;
        var ed = this.editors["col_"+col];
        var xtype = ed.getXType();
        if(this.nowEditInfo)
            var row = this.nowEditInfo.row;
        else
            return;
        
        if(xtype=="combo"){

            this.setFieldValue(col,row,"");

            var cm = this.el.colModel;
            var _record = this.el.store.getAt(row);
            //_record.data[cm.config[col].nameIndex] = "";
            this.el.getStore().getAt(row).set(cm.config[col].nameIndex,"");
            
            var _td = this.el.getView().getCell(row,col);
            _td.innerHTML = "&nbsp;";
            //debugger;
                
            ed.store.removeAll();
            if(disMode) ed.disable();
        }
    },   
    
    setFieldValue : function(col,row,newValue){
        //debugger;
        var cm = this.el.colModel;
        var dataIndex = cm.getDataIndex(col);
        
        this.setFieldValueByDataIndex(row,dataIndex,newValue);
        
        /*if(this.el.getStore().getAt(row)){
            this.el.getStore().getAt(row).set(dataIndex,newValue);
            this.updateBusinessByRowDataIndex(row,dataIndex,newValue);
        }*/
    },
    setFieldValueByDataIndex : function(dataIndex,row,newValue){
        //debugger;
        var cm = this.el.colModel;
        if(this.el.getStore().getAt(row)){
            this.el.getStore().getAt(row).set(dataIndex,newValue);
            this.updateBusinessByRowDataIndex(row,dataIndex,newValue);
        }
    }, 
    
    updateBusinessByRowDataIndex : function(row,dataIndex,value){
        var dataObj   = Sail.getSubObj(this.ownerFrame.businessData,this.config.root);   //取子对象
        var actRow    = this.getActualRow(dataObj,row);
        this.ownerFrame.setBusinessData(dataObj,actRow,dataIndex,value);    //保存到数据结构
    },

    //===================================================================================
    //方法 ： 
    //参数 ： 
    //返回 :  
    //说明 ： 创建可编辑表格列编辑器
    //===================================================================================
    /*onCellClick : function(col,fn){
        debugger;
        col = (typeof col =='number')?this.getHeaderByCol(col):col;
        this.addAction(col,fn);
    },*/
    
    lastFunc : function(){
    }
});

﻿//=======================================================================================
//
//
//
//=======================================================================================



//=======================================================================================
//=======================================================================================
Sail.widget.ext.tree = Sail.extend(Sail.widget,{
    defaultIconcls : 'icon-tree',
    defaultHeight  : 100,
    showTitle      : true,
    events         : [],
    keepEvent      : true,
    resource       : "resource",
    fieldmap       : {text:'name'},
    
    btName : [],
    btEl   : [],
    icons  : [],
    defaultIcon : "mybutton",
    
    initComponent  : function(){
        this.events = [];
    },
    setHeight : function(h){
        this.height = h;
        var treeHeight = this.getTreePanelHeight();
        this.div_tree.el.style.height = treeHeight;
        this.treePanel.setHeight(treeHeight);
    },
    
    getTreePanelHeight : function(){
        var otherHeight = 0;
        otherHeight +=(this.div_tbar!=undefined)?this.div_tbar.getOffset().height:0;
        otherHeight +=(this.div_title!=undefined)?this.div_title.getOffset().height:0;
        otherHeight +=(this.div_splitBar!=undefined)?4:0;

        var sppheight = 0;
        sppheight +=(this.div_tbar!=undefined)?1:0;
        sppheight +=(this.showTitle===true)?1:0;
        
        return this.height-otherHeight+sppheight;
    },
    
    on : function(eventName, handler, scope, options){
        if(this.keepEvent===true){
            this.events.push({
                eventName : eventName,
                handler : handler,
                scope   : scope,
                options : options
            });
        }
        
        if(this.el.getXType()=='treepanel')
            this.el.on(eventName, function(node){handler.call(this,node.attributes.param,node)}, scope, options);
    },
    
    setWidth : function(w){
        this.width = w;
        this.container.setWidth(w);
        this.treePanel.setWidth(w-1);
        
        if(this.el!=undefined && this.el.setWidth!=undefined){
            this.el.setWidth(w);
        }
    },
    setChecked : function(nodes) {

        function toggleChecked(node, checked) {
            try{    // fix for IE6
                node.ui.checkbox.defaultChecked = checked;
                node.attributes.checked = checked;
                node.ui.checkbox.checked = checked;
            }catch(e){
                ;
            }
        };  
        var vs = nodes.split(",");
        for(var i=0;i<vs.length;i++){
            var node = this.el.getNodeById(vs[i]);
            toggleChecked(node, true);
        }
    },
    
    setNodeIcon : function(nodeInfo){
        return "";
    },
    
    create_node:function(node_info, datamap, record, deep) {
        
        var id = node_info[datamap['id'] ? datamap['id'] : 'id']; 
        var text = node_info[datamap['text'] ? datamap['text'] : 'text']; 
        var params = {};
        
        for (k in node_info) {
            if(k=='children')
                params[k] = true;
            else
                params[k] = node_info[k];    
        }
        
        /*
        var checked = node_info[datamap['checked'] ? datamap['checked'] : 'checked'];
        if (checked == 'true')
        {
            checked = true;
        } 
        else if (checked == 'false') 
        {
            checked = false;
        } else {
            checked = '';
        }
        */
        var leaf = (node_info.children && node_info.children[record]!=undefined) ? false : true;
    
        var checked = (this.treeType=='checked')?false:'';
        if(this.selectdisabled!=undefined){
            var ts = ","+this.selectdisabled+",";
            if(ts.indexOf(","+node_info['type']+",")!==-1)
            //if(node_info['type']==this.selectdisabled)
                checked='';
        }
        //debugger;
        
        var nodeConfig = {
            id: id,
            text: text,
            leaf: leaf,
            checked: checked,
            //cls : 'x-tree-node-disabled',
            //iconCls  : 'icon-tab-tree',
            param: params,
            draggable: false
        };
        
        if(this.setNodeCls!=undefined){
            var cls = this.setNodeCls(node_info);
            if(cls!=undefined && typeof cls=='string' && cls.length>0){
                nodeConfig.cls = cls;
            }
        }
        
        if(this.setNodeIcon!=undefined){
            var iconcls = this.setNodeIcon(node_info);
            if(iconcls!=undefined && typeof iconcls=='string' && iconcls.length>0){
                nodeConfig.iconCls = iconcls;
            }
        }
        
        var tree_node = new Ext.tree.TreeNode(nodeConfig);
        var theObj = this;
        if (!leaf) {
            if (node_info.children[record].length) {
                Ext.each(node_info.children[record], function(elN) {
                    tree_node.appendChild(theObj.create_node(elN, datamap, record));
                })        
            } else {
                tree_node.appendChild(theObj.create_node(node_info.children[record], datamap, record));
            }
        }
         
        return tree_node;
    },

    getChecked : function(){
        var ra = new Array();
        
        var nodes = this.el.getChecked();
        if(nodes!=undefined){
            for(var i=0;i<nodes.length;i++){
                var nodeAttributes = nodes[i].attributes;
                
                if(arguments.length==0)
                    ra.push(nodeAttributes["id"]);
                else if(arguments.length==1 && (typeof arguments[0]=='string')){
                    ra.push(nodeAttributes[arguments[0]]);
                }
            }
        }
        return ra;
    },
    getCheckNode : function(){
        var nodes =  this.el.getChecked();
        
        var ra = [];
        for(var i=0;i<nodes.length;i++){
            ra.push(nodes[i].attributes);
        }
        return ra;
    },
    afterLoadData : function(){
    },
    afterLoadDataByUrl : function(){
    },
    
    generate_tree:function(container, url, record_object, record_map, root_visiable) {
        var rv = root_visiable ? root_visiable : false;
        var root_node = new Ext.tree.TreeNode({
            id: 'zzzzzzzzzzzzzzzzzzzz',
            text: 'zzzzzzzzzzzzzzzzzzzz',
            leaf: false
        });    

        //-------------------------------------------------------------------------------
        //增加，for checked tree
        //-------------------------------------------------------------------------------
        function toggleChecked(node, checked) {
            try{    // fix for IE6
                node.ui.checkbox.defaultChecked = checked;
                node.attributes.checked = checked;
                node.ui.checkbox.checked = checked;
            }catch(e){
                ;
            }
        };  
        function parentCheck(node, checked,keepParent) {        //20090818 增加参数 keepParent
            
            var np = node.parentNode;
            while (np) {
                var checkAble = false;
                if (np.isRoot) break;
                for (var i = 0; i < np.childNodes.length; i++) {
                    if (np.childNodes[i].attributes.checked == true) {
                        if (np.attributes.checked == false) {
                            toggleChecked(np, true);
                        }
                        checkAble = true;
                        break;
                    }
                }
                if (checkAble) {
                    np = np.parentNode;
                    continue;   
                } else {
                    if(keepParent===false)                      //增加标志，默认判断为true
                        toggleChecked(np, checked);             //20090818 取消所有子，不取消父 SPSC
                    np = np.parentNode;
                }
            }
        };
        function childCheck(node, checked) {
            var _this = arguments.callee;
            Ext.each(node.childNodes, function(el) {
                toggleChecked(el, checked);
                if (!el.isLeaf()) {
                    _this.call(this, el, checked);
                }
            }); 
        };

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var tree = new Ext.tree.TreePanel({
            enableDD: false,
            autoScroll: true,
            animate: false,
            checkModel: 'cascade', 
            onlyLeafCheckable: false, 
            rootVisible: root_visiable,
            border: false,
            renderTo: container,
            height: 'auto',
            root: root_node,
//20090818 转移事件注册到组件创建后，为了传入this(Sail.widget.ext.tree)
//            listeners: {
//                'checkchange': function(node, checked){
//                    if (node.isLeaf()) {
//                        parentCheck(node, checked);
//                    } else {
//                        childCheck(node, checked);
//                        parentCheck(node, checked);
//                    }
//                }
//            },            
            loader: new Ext.tree.TreeLoader({  
                dataUrl : '',
                baseAttrs: { uiProvider: Ext.ux.TreeCheckNodeUI }   
            })          
        });    
        
        tree.on('checkchange',function(node, checked){
            if (node.isLeaf()) {
                parentCheck(node, checked,this.keepParent);
            } else {
                childCheck(node, checked);
                parentCheck(node, checked,this.keepParent);
            }
        },this);
                
        var p = new Ext.data.HttpProxy({
        	url: url,
        	method: 'POST'
        });
    
        p.on("loadexception", function(t, o, response, e) {
            if (e) throw e;
            //debugger;
            Ext.Msg.alert('注意：', '树组件读取数据出错!');
        });
        var theObj = this;
        p.load(null, {
            read: function(response) {
                var t = eval('(' + response.responseText + ')');
                
                //debugger;
                if (t.dataset.response.success == 'false') {
                    Ext.Msg.alert('注意：', t.dataset.response.content);
                    return null;
                }
                
                /*
                ** 获取映射
                */
                if (record_map) {
                    var datamap = record_map;
                } else {
                    var maparray = t.dataset.datamap.replace(/\s/, '').split(',');
                    var datamap = {};
                    Ext.each(maparray, function(el) {
                        var key = el.split('=')[1];
                        var value = el.split('=')[0];
                        datamap[key] = value;
                    });                  
                }
                
                if (record_object) {
                    var record = record_object;//取得对象标志
                } else {
                    var record = t.dataset.objects;//取得对象标志
                }
            
                /*
                var maparray = t.dataset.datamap.replace(/\s/, '').split(',');
                var datamap = {};
                Ext.each(maparray, function(el) {
                    var key = el.split('=')[1];
                    var value = el.split('=')[0];
                    datamap[key] = value;
                });            
                
                var record = t.dataset.objects;//取得对象标志
                */

                //*
                if (t.dataset[record].length) {
                    Ext.each(t.dataset[record], function(elN) {
                        //debugger;
                        root_node.appendChild(theObj.create_node(elN, datamap, record));
                    })        
                } else {
                    root_node.appendChild(theObj.create_node(t.dataset[record], datamap, record));
                }
                //*/
                
                //root_node.appendChild(theObj.create_node(t.dataset[record], datamap, record));
                tree.expandAll();
                //debugger;
                theObj.afterLoadData();
                theObj.afterLoadDataByUrl();
            }
        }, function() {}, tree);  
        return tree;
    },
    reload : function(){
        if(this.el.getXType()=='treepanel')
            this.el.destroy();
        
        var url = (arguments.length>0)?arguments[0]:this.url;
        //debugger;
        this.el = this.generate_tree(this.OCBC, url,this.resource,this.fieldmap);
        
        if(this.keepEvent===true){
            for(var i=0;i<this.events.length;i++){
                var e = this.events[i];
                this.el.on(e.eventName,function(node){e.handler.call(this,node.attributes.param)},e.scope,e.options)
            }
        }
        
    },
    
    getTabHTML : function(config){
        var sb = new Sail.stringBuffer();
        
        sb.push("<table style='cursor:hand' height=23 cellspacing=0 >");
        sb.push("<tr height=23>");
        sb.push("<td class='form_left'   width=3></td>");

        this.activeClass = 'form_center_active';
        this.normalClass = 'form_center';
        var _class = (config.isActive===true)?this.activeClass:this.normalClass;

        if(this.noIcon!==true){
            sb.push("<td class='"+_class+"' width=12></td>");
            sb.push("<td class='"+_class+"' width=16>");
            var _icon = (config.iconcls==undefined)?this.defaultIconcls:config.iconcls;
            sb.push("<div class='"+_icon+"' style='width:16;height:16'></div>");
            sb.push("</td>");
            sb.push("<td class='"+_class+"' width=2></td>");
        }else{
            sb.push("<td class='"+_class+"' width=40></td>");
        }
        sb.push("<td class='"+_class+"' height=23 >"+config.title+"</td>");
        sb.push("<td class='"+_class+"' width=40></td>");
        sb.push("<td class='form_right'  width=3></td>");
        sb.push("</tr></table>");

        return sb.toString();
    },

    
    createToolBar : function(){
        if(this.tbar!=undefined && (typeof this.tbar=='object')){
            var tbarheight = 26;
            this.div_tbar = new Sail.DIV({
                left  : 0,
                top   : 0,
                width : '100%',
                height: tbarheight,
                parent: this.getOCD()
            });
            
            var wconfig = {
                parentDiv   : this.div_tbar.getEl(),
                ownerFrame  : this.ownerFrame,
                ownerGroup  : this.ownerGroup,
                owner       : this,
                page        : this.page,
                widgetPrefix: this.widgetPrefix,
                left    : 0,
                top     : 0,
                width   : this.div_tbar.getOffset().width,
                height  : this.div_tbar.getOffset().height
            };
            Sail.apply(wconfig,this.tbar);
            
            if(wconfig.textColor==undefined) wconfig.textColor = '#15428B';
            
            var w = eval("new "+wconfig.widgetPrefix+""+wconfig.type+"();");
            var _size = w.create(wconfig);                 //创建 组件
            
            return tbarheight;
        }
        return 0;
    },
    
    createTitleBar : function(config){
        if(this.showTitle===true){
            var titleBarHeight = 22;
            this.div_title = new Sail.DIV({
                left  : 4,
                top   : config.top||0,
                width : '100%',
                height: titleBarHeight,
                parent: this.getOCD(),
                zIndex: 10
            });
            
            this.div_title.setHTML(this.getTabHTML({
                isActive:true,
                iconcls : (this.iconcls==undefined)?this.defaultIconcls:this.iconcls,
                top:0,left:4,height:23,
                title:this.title
            }));
            
            //debugger;
            
            var w1 = this.div_title.el.children[0].offsetWidth;
            var _left  = w1+14;
            var _width = this.div_title.getOffset().width-_left-20;
            this.createBtBar(_left,_width);
            
            return titleBarHeight;
        }
        return 0;
    },

    createBtBar: function(_left,_width){
        this.btbar = new Sail.DIV({
            parent: this.div_title,
            style : {left: _left,top: -2,width:_width,border:'0px #0000ff solid'}
        });

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.buttons!=undefined){
            this.formatButtons();

            for(var i=0;i<this.buttons.length;i++)
                this.addButton(this.buttons[i].name,this.buttons[i].icon);
        }
        
        var _html = ["<table width='100%' border=0 cellpading=0 cellspacing=2><tr height=21><td width=100%></td>"];
        for(var i=0;i<this.btName.length;i++){
            _html.push("<td align=right><div id='"+this.btbar.getID()+"_"+i+"'></div></td>");
        }
        _html.push("</tr></table>");
        this.btbar.el.innerHTML = _html.join("");
        

        for(var i=0;i<this.btName.length;i++){
            this.btEl.push(new Ext.Button({
                text:"　"+this.btName[i],
                iconCls:'x-btn-left '+this.icons[i],
                cls: 'x-btn-text-icon',
                renderTo:this.btbar.getID()+"_"+i
            }));
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.isSearch===true){
            //this.addHandler('查询',this.defaultSearchClick);
            this.addHandler('重置',this.reset,this);
        }
    }, 

    formatButtons : function(){
        if(this.buttons==undefined) return;
        
        var nb = [];
        for(var i=0;i<this.buttons.length;i++){
            var o = {name:'',icon:this.defaultIcon};
            if(typeof this.buttons[i]=='object'){
                Sail.apply(o,this.buttons[i]);
            }else{
                o.name=this.buttons[i];
            }
            nb.push(o);
        }
        this.buttons = [].concat(nb);
    },
    getButton : function(name){
        for(var i=0;i<this.btName.length;i++){
            if(this.btName[i]==name)
                return this.btEl[i];
        }
        return null;
    },
    addButton : function(name,icon){
        var haveflag = false;
        for(var i=0;i<this.btName.length;i++){
            if(this.btName[i]==name)
                haveflag=true;
        }
        if(!haveflag) {
            this.btName.push(name);
            this.icons.push(icon);
        }
    },
    addHandler: function(name,handler,scope){
        var bt = this.getButton(name);
        if(bt!=null) {
            bt.on('click',handler,scope);
        }else{
            alert('没有找到按钮：'+name);
        }
    },



    createSplitBar : function(config){
        if(this.showTitle===true){
            this.div_splitBar = Sail.addDiv2(this.getOCD(),{className:'form_bar'});
            Sail.applyStyle(this.div_splitBar,{
                width:'100%',
                left:0,top:config.top,
                position:"absolute",
                zIndex:9
            });
            return config.top+4;
        }   
        return config.top||0;     
    },
    
    createTreeContainer : function(config){
        this.div_tree = new Sail.DIV({
            left  : 0,
            top   : config.top||0,
            width : '100%',
            height: 100,
            parent: this.getOCD(),
            zIndex: 10
        });
        
        return this.div_tree.getEl();
    },
    
    createWidgetElement:function(){
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var tbarHeight = this.createToolBar();                              //
        var titlebarHeight = this.createTitleBar({top:tbarHeight});         //
        var treeTop = this.createSplitBar({top:tbarHeight+titlebarHeight}); //
        var container = this.createTreeContainer({top:treeTop-((treeTop==0)?0:1)});          //
            
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.collapseBarWidth = 1;
        var panelConfig = {
            animCollapse:false,
            labelAlign: 'top',
            bodyStyle:'padding:5px',
            width: this.width-this.collapseBarWidth,
            height:this.height-56,
            autoWidth: this.autoWidth,
            autoScroll:true,
            renderTo:container,
            items: [{
                layout:'column',
                border:false
            }]
        };
        
        if(this.border!=undefined) panelConfig.border = this.border;
        
        this.el = new Ext.FormPanel(panelConfig);
        this.treePanel = this.el;
        
        if(this.collapseBar ===true){
            var c = {
                parent: container,
                style : {left: this.width-this.collapseBarWidth,top: 0,width:this.collapseBarWidth,height:'100%',backgroundColor:'#99BBE8',border:'0px #99BBE8 solid'}
            };
            this.collapseBarDiv = new Sail.DIV(c);
        
        }
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.OCBC   = this.el.body.dom;
        if(this.url!=undefined && this.url!="")
            this.el = this.generate_tree(this.OCBC, this.url,this.resource,this.fieldmap);
    }
});


//=======================================================================================
//=======================================================================================
Sail.widget.ext.imgBox = Sail.extend(Sail.widget.ext.tree,{
    defaultIconcls : 'icon-tabs',
    showTitle      : true,
    showBorder     : true,
    
    getIntendingHeight : function(){
        if(this.imgHeight!=undefined){
            if(this.showTitle==true) return this.imgHeight+28;
            else {
                return (this.showBorder==true)?(this.imgHeight+2):this.imgHeight;
            }
        }else{
            return (this.defaultHeight==undefined)?100:this.defaultHeight;
        }
    },
    
    setHeight : function(h){
        this.height = h;

        this.div_tree.setHeight(this.getTreePanelHeight());
    },
    setWidth : function(w){
        this.width = w;
        this.container.setWidth(w);
        //debugger;
    },
    createTreeContainer : function(config){
        var _height = this.getTreePanelHeight();
        
        var config = {
            left  : 0,
            top   : config.top||0,
            width : '100%',
            height: _height,
            parent: this.getOCD(),
            zIndex: 10
        };
        
        if(this.showBorder===true)  config.border = '1px #99BBE8 solid';
        
        this.div_tree = new Sail.DIV(config);
        
        return this.div_tree.getEl();
    },
    
    createWidgetElement:function(){
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var titlebarHeight = this.createTitleBar({top:0});                          //
        var treeTop = this.createSplitBar({top:titlebarHeight});                    //
        var container = this.createTreeContainer({top:treeTop-((treeTop==0)?0:1)}); //

        this.el = this.div_tree;
        
        if(this.img!=undefined && this.img!=''){
            this.imgEl = document.createElement( "IMG" );     //
            this.imgEl.src = this.img;
            var height = this.imgEl.height;
            var width  = this.imgEl.width;

            this.div_img = new Sail.DIV({
                left  : 0,
                top   : 0,
                width : width,
                height: height,
                parent: this.div_tree
            });

            this.div_tree.applyStyle({
                overflow:'auto',
                backgroundRepeat:'no-repeat',
                backgroundImage : "url("+this.img+")"
            });
            
            if(this.hotspots!=undefined){
                Ext.get(this.div_img.getID()).on('click',function(e){
                    var index = -1;
                    for(var i=0;i<this.hotspots.length;i++){
                        var item = this.hotspots[i].range;
                        var hotspot = new Sail.rect(item.left,item.top,item.width,item.height);
                        
                        if(hotspot.pointInRect(e.browserEvent.offsetX,e.browserEvent.offsetY)){
                            index = i;
                            break;
                        }
                    }

                    if(index!=-1){
                        this.hotspots[index].handler.apply(this);
                    }
                },this);
            }            
        }
    }
});


//=======================================================================================
//=======================================================================================
Sail.widget.ext.listChoice = Sail.extend(Sail.widget,{
    defaultHeight:150,
    
    setHeight : function(h){
        //debugger;
    },
    createListTitle : function(config){
        config.parent = this.getOCD();
        config.border = '0px #99BBE8 solid';
        config.style  = {overflow:'auto',color:'#FF8600',paddingLeft:2};
        return new Sail.DIV(config);
    },
    createListTable : function(config){
        config.parent = this.getOCD();
        config.border = '1px #99BBE8 solid';
        config.style  = {overflow:'auto'};
        return new Sail.DIV(config);
    },
    createTableForList : function(config){
        
        this.tableT = new Ext.Template(
            '<table width=100% border=0 cellpading=0 cellspacing=0 style={tstyle}>',
            '<thead>{cells}</thead>',
            '</table>'
        );

        this.hcell = new Ext.Template(
            "<tr height=20 onmouseover='this.style.backgroundColor=\"#99BBE8\";'",
            " onmouseleave='this.style.backgroundColor=\"#ffffff\";'",
            ">",
            '<td id={id} style="font:normal 12px verdana;cursor:hand;padding-left:4px;">',
            '{value}',
            "</td></tr>"
        );
        
        var list = config.data;
        var cb = [];
        
        for(var i=0;i<list.length;i++){
            var item = list[i];
            if(item[this.fieldValue]=="") continue;
            
            var p = {value:item[this.fieldText],id:this.name+"_"+item[this.fieldValue]};
            cb.push(this.hcell.apply(p));
        }
        var html = this.tableT.apply({cells: cb.join(""), tstyle:''});
        
        config.target.setHTML(html);
    },
    
    
    createBtDiv : function(config){
        config.parent = this.getOCD();
        //config.border = '1px #99BBE8 solid';
        config.style  = {overflow:'auto'};
        var div = new Sail.DIV(config);
        
        var minHeight = 24*4+5;
        var btTable = new Ext.Template(
            '<table width=100% border=0 cellpading=0 cellspacing=0>',
            '<thead>{cells}</thead>',
            '</table>'
        );
        var btTR = new Ext.Template(
            "<tr height=23>",
            '<td >',
            '<div id={id} align=center></div>',
            "</td></tr>"
        );

        var cb = [];
        for(var i=0;i<4;i++){
            var p = {id:'yjjdiv_'+i};
            cb.push(btTR.apply(p));
        }        
        var html = btTable.apply({cells: cb.join("")});
        
        div.setHTML(html);
        
        this.btName = ["全部","所选","所选","全部"];
        this.btEl = [];
        this.btIcons = ["lc_bt_add","lc_bt_add","lc_bt_del3","lc_bt_del3"];
        
        for(var i=0;i<4;i++){
            this.btEl.push(new Ext.Button({
                text:"　"+this.btName[i],
                iconCls:'x-btn-left '+this.btIcons[i],
                cls: 'x-btn-text-icon',
                renderTo:"yjjdiv_"+i
            }));
        }
        
        return div;
    },
    //===================================================================================
    //方法 ： bt event
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    
    //===================================================================================
    //方法 ： load
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    onLoadDataSuccess : function(data,action,options){
        this.fieldText = (this.fieldText==undefined)?"text":this.fieldText;
        this.fieldValue= (this.fieldValue==undefined)?"code":this.fieldValue;
        this.root = (this.root==undefined)?"dataset.simplecombobox":this.root;

        var list = Sail.getSubObj(data,this.root);
        this.createTableForList({target:this.leftTableDiv,data:list});
    },
    onLoadDataFailure : function(data,action,options){
        //debugger;
        alert("读取数据失败！");
    },
    load : function(){
        Sail.request({
            url    : this.url,  
            method : "GET",   
            scope  : this,
            success: function(action,options){
                var _data = eval("("+action.responseText+")"); 
                
                var flag = Sail.getSubObj(_data,"dataset.response.success");
                
                if(flag=="true")    
                    options.scope.onLoadDataSuccess(_data,action,options);
                else                
                    options.scope.onLoadDataFailure(_data,action,options);
                    
            },
            failure: function(action,options){
                var _data = {"dataset":{"response":{"content":"数据获取失败！404错误！","success":"false"}}};
                options.scope.onLoadDataFailure(_data,action,options);
            }
        });        
    },
    
    //===================================================================================
    //方法 ： create
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createWidgetElement:function(){
        //debugger;

        this.btBarWidth = (this.btBarWidth==undefined)?90:this.btBarWidth;
        var ltWidth = (this.width-this.btBarWidth-10)/2;
        var ltHeight= this.height-24;
        

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var config = {left:0,top:2,width:ltWidth,height:20};
        this.leftTitleDiv = this.createListTitle(config);
        this.leftTitleDiv.setText('未选择：');

        var config = {left:0,top:20,width:ltWidth,height:ltHeight};
        this.leftTableDiv = this.createListTable(config);
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var config = {left:ltWidth+5,top:30,width:this.btBarWidth,height:ltHeight};
        this.moveBtDiv = this.createBtDiv(config);

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var config = {left:ltWidth+10+this.btBarWidth,top:2,width:ltWidth,height:ltHeight};
        this.leftTitleDiv = this.createListTitle(config);
        this.leftTitleDiv.setText('已选择：');

        var config = {left:ltWidth+10+this.btBarWidth,top:20,width:ltWidth,height:ltHeight};
        this.rightTableDiv = this.createListTable(config);

        this.el = {};
        
        if(this.url!=undefined && this.url!=''){
            this.load();
        }
        //this.el = this.div_tree;
        
    }
});﻿
Sail.widget.ext.tabComponent = Sail.extend(Sail.widget,{
    showTitle : true,
    border    : true,
    
    defaultIconcls : 'icon-tab',
    defaultHeight  : 100,
    
    moveTimer : null,
    moveStep  : 0,
    moveCount : 0,

    activeIndex : 0,
    
    //enableClose : true,                //是否可以关闭标志
    //createMode  : 'when-created',       //tab创建模式：当创建组件时创建/当点击时创建
    
    moveBarWidth : 32,
    activeZIndex : 100,
    
    //mutualMode   : true,
    
    //===================================================================================
    //方法 ： some func for init before create element
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    initComponent : function(){
        
        Sail.widget.ext.tabComponent.superclass.initComponent.call(this);

        this.addEvents('tabclick');

        this.showTitle = true;              //showTitle 恒等于 true
        this.items     = this.items ||[];
        
        //-------------------------------------------------------------------------------
        this.title     = (this.title==undefined && this.titles!=undefined)?this.titles:this.title;
        this.title     = (typeof this.title =='string')?[this.title]:this.title;
        this.title     = this.title||[];
        this.showTitle = (this.title.length==0)?false:this.showTitle;
        this.count     = this.title.length;

        //-------------------------------------------------------------------------------
        this.createFlag= [];
        for(var i=0;i<this.count;i++){
            this.createFlag.push(false);    //各个tab 是否已创建标志
        }
        
        //-------------------------------------------------------------------------------
        this.repairCreateMode();            //各个tab 创建模式(create/click)
        this.repairEnableClose();           //各个tab 是否允许关闭
        this.repairIconCls();               //各个tab 图标样式
        
        this.initTitleWidth();
    },
    
    repairCreateMode  : function(){
        var len = this.count;
        
        if(typeof this.createMode =='string'){
            var backup = this.createMode;
            this.createMode = [];
            for(var i=0;i<len;i++){
                this.createMode.push(backup);
            }
        }else if(this.createMode instanceof Array){
            for(var i=0;i<len;i++){
                if(this.createMode[i]==undefined){
                    this.createMode[i]='when-created';
                }
            }
        }else{
            this.createMode = [];
            for(var i=0;i<len;i++){
                this.createMode.push('when-created');
            }
        }
    },
    
    repairEnableClose : function(){
        var len = this.count;
        
        if(typeof this.enableClose =='boolean'){
            var backup = this.enableClose;
            this.enableClose = [];
            for(var i=0;i<len;i++){
                this.enableClose.push(backup);
            }
        }else if(this.enableClose instanceof Array){
            for(var i=0;i<len;i++){
                if(this.enableClose[i]==undefined){
                    this.enableClose[i]=false;
                }
            }
        }else{
            this.enableClose = [];
            for(var i=0;i<len;i++){
                this.enableClose.push(false);
            }
        }
    },
    
    repairIconCls : function(){
        var len = this.count;
        
        if(typeof this.iconCls =='string'){
            var backup = this.iconCls;
            this.iconCls = [];
            for(var i=0;i<len;i++){
                this.iconCls.push(backup);
            }
        }else if(this.iconCls instanceof Array){
            for(var i=0;i<len;i++){
                if(this.iconCls[i]==undefined){
                    this.iconCls[i]= this.defaultIconcls;
                }
            }
        }else{
            this.iconCls = [];
            for(var i=0;i<len;i++){
                this.iconCls.push(this.defaultIconcls);
            }
        }
    },
    
    initTitleWidth : function(){
        this.standardTW = [];
        this.activeTW   = [];
        var w = 0,title="";
        for(var i=0,len=this.getCount();i<len;i++){
            title = this.title[i];
            w = Sail.getLabelWidth(title,"12px verdana");
            this.standardTW.push(w);
            w = Sail.getLabelWidth(title,"bold 12px verdana");
            this.activeTW.push(w);
        }
    },
    
    //===================================================================================
    //方法 ： some func for 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getCount : function(){
        return this.title.length;
        //return this.count;
    },
    
    getTabTotalWidth : function(){
        var allTitleWidth = this.standardTW.sum()+this.activeTW[this.activeIndex]-this.standardTW[this.activeIndex];
        return 2+allTitleWidth+72*this.getCount();
    },
    
    getTabWidthByIndex : function(index){
        var tw = (this.activeIndex==index)?this.activeTW[index]:this.standardTW[index];
        return (2+3+6+16+2+tw+40+3)||0;
    },
    
    getTabLeft : function(index){
        var left = 0;
        for(var i=0;i<index;i++){
            left+=this.getTabWidthByIndex(i);
        }
        return left;
    },
    getTabRight : function(index){
        return this.getTabLeft(index+1)+2;
    },

    getMoveBarWidth : function(){
        return this.moveBarWidth;
    },
    getMoveButtonLeft : function(){
        return this.width - 4- this.getMoveBarWidth();
    },

    
    //===================================================================================
    //方法 ： some func for change size 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setHeight : function(h){
        this.height = h;
        this.container.setHeight(h);

        var bodyHeight = this.getBodyHeight();
        this.body.setHeight(bodyHeight);

        for(var i=0;i<this.children.length;i++){
            var childer = this.children[i];
            childer.setHeight(bodyHeight-2);
            
            if(this.createFlag[i]==true){
                if(this.tabLayouts[i]!=undefined)
                    this.tabLayouts[i].reLayout({height:bodyHeight-2});
            }
        }
    },
 
    setWidth : function(w){
        this.width = w;
        this.container.setWidth(w);

        this.body.setWidth(this.width);
        this.div_splitBar.setWidth(this.width);
        this.reCreateTitleBar();

        for(var i=0;i<this.children.length;i++){
            var childer = this.children[i];
            childer.setWidth(this.width);
            
            if(this.createFlag[i]==true){
                if(this.tabLayouts[i]!=undefined)
                    this.tabLayouts[i].reLayout({width:this.width});
            }
        }
    },
    
    setSize : function(w,h){
        this.width  = w;
        this.height = h;
        this.container.setWidth(w);
        this.container.setHeight(h);

        var bodyHeight = this.getBodyHeight();
        this.body.setHeight(bodyHeight);

        this.body.setWidth(this.width);
        this.div_splitBar.setWidth(this.width);
        this.reCreateTitleBar();

        for(var i=0;i<this.children.length;i++){
            var childer = this.children[i];
            childer.setWidth(this.width);
            childer.setHeight(bodyHeight-2);
            
            if(this.createFlag[i]==true){
                if(this.tabLayouts[i]!=undefined){
                    this.tabLayouts[i].reLayout({width:this.width,height:bodyHeight-2});
                }
            }
        }
        
    },
    
    refreshBody : function(){
    },
    
    //===================================================================================
    //方法 ： some func for move bar button  
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    tabsScroll2 : function(step,mode){
        mode = (mode==undefined)?'increase':mode;
        this.div_title.scroll2('h',step,mode);
    },
    
    btMove2Left_over : function(){},
    btMove2Left_out : function(){},
    btMove2Left_disable : function(){
        if(!this.btMove2Left.hasClass('icon-tabs-m2-left-disabled'))
            this.btMove2Left.addClass('icon-tabs-m2-left-disabled');
    },
    btMove2Left_enable : function(){
        if(this.btMove2Left.hasClass('icon-tabs-m2-left-disabled'))
            this.btMove2Left.removeClass('icon-tabs-m2-left-disabled');
    },
    btMove2Left_click : function(){
        //debugger;
        var theobj = this;
        this.moveStep = 0;
        theobj.moveCount=0;
        
        this.moveTimer = setInterval(function(){
            theobj.moveCount++;
            theobj.tabsScroll2(theobj.moveStep);
            if(theobj.div_title.el.scrollLeft==0){
                theobj.btMove2Left_disable();
                theobj.stopTimer();
            }

            theobj.btMove2Right_enable();
            
            if(theobj.moveCount<10){
                theobj.moveStep+=-1;
            }else{
                theobj.moveStep+=-2;
                theobj.moveStep = (theobj.moveStep>0)?0:theobj.moveStep;
            }
            
            if(theobj.moveCount>20){
                theobj.stopTimer();
            }
        },10);
    },


    btMove2Right_over : function(){},
    btMove2Right_out : function(){},
    btMove2Right_disable : function(){
        if(!this.btMove2Right.hasClass('icon-tabs-m2-right-disabled'))
            this.btMove2Right.addClass('icon-tabs-m2-right-disabled');
    },
    btMove2Right_enable : function(){
        if(this.btMove2Right.hasClass('icon-tabs-m2-right-disabled'))
            this.btMove2Right.removeClass('icon-tabs-m2-right-disabled');
    },
    btMove2Right_click : function(){
      
        var theobj = this;
        this.moveStep = 0;
        theobj.moveCount=0;
        
        this.moveTimer = setInterval(function(){
            theobj.moveCount++;
            theobj.tabsScroll2(theobj.moveStep);
            if(theobj.div_title.el.scrollLeft>=theobj.moveLimit){
                theobj.btMove2Right_disable();
                theobj.stopTimer();
            }
            
            theobj.btMove2Left_enable();
            
            if(theobj.moveCount<10){
                theobj.moveStep+=1;
            }else{
                theobj.moveStep+=2;
                theobj.moveStep = (theobj.moveStep<0)?0:theobj.moveStep;
            }
            
            if(theobj.moveCount>20){
                theobj.stopTimer();
            }
        },10);
    },
    
    stopTimer:function(){
        this.moveCount=0;
        this.moveStep = 0;
        clearInterval(this.moveTimer);
    },
    
    //===================================================================================
    //方法 ： some func for reset tabs when click 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getTabHTML : function(config){
        if(this.tp_td == undefined){
            this.tp_td = new Sail.Template(
                "<td id={tdid} width={tdWidth}>",
                    "<table cellspacing=0 cellpadding=0 border=0 style='cursor:hand;table-layout:fixed'>",
                        "<tr height=23>",
                            "<td class='tc-tab-leftspac' width=2></td>",         //标签左空白间隔
                            "<td class='{leftBorder}' width=3></td>",            //左边框
                            "<td class='{commentCls}' width=6></td>",            //图标左留白
                            "<td class='{commentCls}' width=16>",                //图标
                                "<div class='{iconCls}' style='width:16;height:16'></div>",
                            "</td>",
                            "<td class='{commentCls}' width=2></td>",            //图标文本间隔
                            "<td class='{commentCls}' height=23 width={titleW} style='padding-top:2px'>{title}</td>", //标签文本
                            "<td class='{commentCls}' width=40 align=right>",
                                //"<div class='icon-tabs-close' style='width:13;'></div>",
                            "</td>",           //右留白
                            "<td class='{rightBorder}' width=3></td>",            //右边框
                        "</tr>",
                    "</table>",
                "</td>"
            );
        }
        
        return this.tp_td.apply({
            leftBorder  : (config.activeIndex)?"tc-tab-leftborder-active" :"tc-tab-leftborder",
            rightBorder : (config.activeIndex)?"tc-tab-rightborder-active":"tc-tab-rightborder",
            commentCls  : (config.activeIndex)?"tc-tab-centen-active":"tc-tab-centen",
            iconCls     : (config.activeIndex)?"tc-tab-icon":"tc-tab-icon-dis",
            
            tdid        : config.id,
            titleW      : config.titleWidth,
            tdWidth     : config.tdWidth,
            title       : config.title
        });
        
    },

    getTitleBarHTML : function(config){              //创建一个tabs标签tab的HTML代码
        this.tp_table = new Sail.Template(
            '<table style="cursor:hand;table-layout:fixed" height=23 cellspacing=0 >',
                '<tr height=23>',
                '<td class="tc-tab-leftspac" width=2></td>',
                '{td}</tr>',
            '</table>'
        );


        if(typeof config.title =='string'){
            config.title = [config.title];
        }
        config.activeIndex = config.activeIndex ||0;
        
        var tds = [];
        var td  = "";
        for(var i=0,len=config.title.length;i<len;i++){
            var w = Sail.getLabelWidth(config.title[i],((i==config.activeIndex)?"bold 12px verdana":"12px verdana"));
            
            td = this.getTabHTML({
                id          : config.idprefix+"-"+i,
                activeIndex : (i==config.activeIndex)?true:false,
                titleWidth  : w,
                tdWidth     : this.getTabWidthByIndex(i),
                title       : config.title[i]
            });

            tds.push(td);
        }
        
        var table = this.tp_table.apply({
            td:tds.join("")
        });
        
        return table;
    },
    
    bindEvent2Tab  : function(){
        this.titleTD = [];
        for(var i=0;i<this.getCount();i++){
            var tdid = this.div_title.getID()+"-"+i;
            var td = Ext.get(tdid);
            this.titleTD.push(td.dom);
            td.on('click',this.onTabClick,this);
        }
    },
    
    onTabClick : function(e,target){
        var clickTD = arguments[0].target.parentElement.parentElement.parentElement.parentElement;
        clickTD     = (arguments[0].target.tagName=='DIV')?clickTD.parentElement:clickTD;
        var index   = parseInt(clickTD.id.split('-')[1],10);
        
//        if(target.className=='icon-tabs-close'){
//            this.onTabClose(index);
//            return;
//        }

        if(index==this.activeIndex) return;
        if(!isNaN(index)){
            this.setActiveTab(index);
        }
        
        this.fireEvent('tabclick',this,e);
    },

    //on2 : function(eventName, handler, scope, options){
    //    debugger;
    //    this.on(eventName, handler, scope, options);
    //},

    
    onTabClose : function(closeIndex){
//        if(this.title.length==1) return;
//        
//        this.title.splice(closeIndex,1);
//
//        var html = this.getTitleBarHTML({
//            title:this.title,activeIndex:this.activeIndex,idprefix : this.div_title.getID(),
//            iconcls : (this.iconcls==undefined)?this.defaultIconcls:this.iconcls
//        })
//        this.div_title_son.setHTML(html);
//        this.bindEvent2Tab();   
//
//        if(this.needMoveBar()){
//            this.moveLimit = this.div_title.el.scrollWidth - this.div_title.el.offsetWidth;
//        }             
    },
    

    //===================================================================================
    //方法 ： some func for setActiveTab 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    setActiveTab : function(index){
        this.resetTabsTitle(index);
        this.activedChilder(index);
    },

    resetTabsTitle : function(newActiveIndex){
        //debugger;
        var oldActiveIndex = this.activeIndex;      //保存旧的当前索引
        this.activeIndex   = newActiveIndex;        //设置新的当前索引
        
        var oldTDID = this.div_title.getID()+"-"+oldActiveIndex;
        var newTDID = this.div_title.getID()+"-"+newActiveIndex;
        this.setTabClass(oldTDID,oldActiveIndex,false);
        this.setTabClass(newTDID,newActiveIndex,true);

        this.moveLimit = this.div_title.el.scrollWidth - this.div_title.el.offsetWidth;
        
        if(this.btMove2Left==undefined) return;
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var left = this.getTabLeft(newActiveIndex);
        if(left<this.div_title.el.scrollLeft){
            this.tabsScroll2(-this.div_title.el.scrollLeft+left+((newActiveIndex==0)?0:2));
            this.btMove2Right_enable();
            
            if(this.div_title.el.scrollLeft==0){
                this.btMove2Left_disable();
            }
        }

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var right = this.getTabRight(newActiveIndex);
        if(right>(this.div_title.el.offsetWidth+this.div_title.el.scrollLeft)){
            this.tabsScroll2(right-this.div_title.el.offsetWidth,'');
            this.btMove2Left_enable();

            if(this.div_title.el.scrollLeft>=this.moveLimit){
                this.btMove2Right_disable();
            }
            
        }else{
            this.btMove2Right_enable();
        }
    },
    
    setTabClass : function(tabid,index,isActive){

        var TD = document.getElementById(tabid);
        var TR = TD.children[0].rows[0];
        
        TR.cells[1].className=(isActive)?"tc-tab-leftborder-active" :"tc-tab-leftborder"
        for(var i=2;i<7;i++){
            TR.cells[i].className = (isActive)?"tc-tab-centen-active":"tc-tab-centen";
        }
        TR.cells[7].className=(isActive)?"tc-tab-rightborder-active" :"tc-tab-rightborder"

        TR.cells[3].children[0].className=(isActive)?"tc-tab-icon" :"tc-tab-icon-dis"

        var w = Sail.getLabelWidth(this.title[index],(isActive)?"bold 12px verdana":"12px verdana");
        TR.cells[5].width = w;
        
        TD.width = this.getTabWidthByIndex(index);
    },

    activedChilder : function(tabIndex,mode){
        if(this.mutualMode===true && mode!==true) return;
        
        this.activeZIndex++;
        this.children[tabIndex].el.style.zIndex=this.activeZIndex;
        
        if(this.createFlag[tabIndex]==false){
            this.doLayoutByIndex(tabIndex);
        }
    },

    //===================================================================================
    //方法 ： some func for bars 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    reCreateTitleBar : function(){
        var needFlag = this.reCreateMoveBar();
        
        var mbWidth  = (needFlag)?this.getMoveBarWidth():0;
        var width    = this.width - ((mbWidth==0)?0:mbWidth+18);
        
        this.div_title.setWidth(width);        
        this.div_title.addClass((mbWidth==0)?'tc-tb':'tc-tb-needMove-right');

        if(needFlag){
            this.moveLimit = this.div_title.el.children[0].offsetWidth - this.div_title.el.offsetWidth;
        }
    },
    
    createTitleBar : function(){          //创建标题栏
        
        //-------------------------------------------------------------------------------
        //如果需要，创建移动tab的左右按钮栏
        //-------------------------------------------------------------------------------
        var mbWidth = (this.needMoveBar())?this.createMoveBar():0;
        
        //-------------------------------------------------------------------------------
        //创建标题栏容器
        //-------------------------------------------------------------------------------
        this.titleBarHeight = (this.titleBarHeight==undefined)?23:this.titleBarHeight;
        
        var width = this.width - ((mbWidth==0)?0:mbWidth+18);
        
        this.div_title = new Sail.DIV({
            left  : 0,
            top   : 0,
            width : width,
            height: this.titleBarHeight,
            zIndex: 10,
            border: "0px #ff0000 solid",

            parent: this.getOCD()
        });
        this.div_title.addClass((mbWidth==0)?'tc-tb':'tc-tb-needMove-right');
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.div_title_son = new Sail.DIV({
            left  : 0,
            top   : 0,
            parent: this.div_title,
            //border: "1px #ff0000 solid",
            zIndex : 10
        });
    
        var html = this.getTitleBarHTML({
            title:this.title,activeIndex:this.activeIndex,idprefix : this.div_title.getID(),
            iconcls : (this.iconcls==undefined)?this.defaultIconcls:this.iconcls
        })

        this.div_title_son.setHTML(html);
        this.bindEvent2Tab();
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        if(this.needMoveBar()){
            this.moveLimit = this.div_title.el.scrollWidth - this.div_title.el.offsetWidth;
          
        }
            
        return this.titleBarHeight;
    },

    createSplitBar : function(top){          //创建一个分隔栏
        this.splitBarHeight = 4;
        this.div_splitBar = new Sail.DIV({
            width :'100%',
            left  :0,
            top   :top-1,
            parent: this.getOCD(),
            border:'#8DB2E3 1px solid',
            zIndex:9
        });
        this.div_splitBar.addClass('form_bar');        
        return this.splitBarHeight;
    },

    getIndexByTitle : function(title){
        var len = this.getCount();
        for(var i=0;i<len;i++){
            if(this.title[i]==title) return i;
        }
        return -1;
    },

            
    changeTitle : function(oldTitle,newTitle){
        
        //-------------------------------------------------------------------------------
        //根据旧标题文本获得其在tabs中的索引
        //-------------------------------------------------------------------------------
        var index = (typeof oldTitle =='string')?this.getIndexByTitle(oldTitle):oldTitle;
        if(index==-1) return false;
        
        //-------------------------------------------------------------------------------
        //根据索引，修改 全局记录
        //-------------------------------------------------------------------------------
        this.standardTW[index]= Sail.getLabelWidth(newTitle,"12px verdana");;
        this.activeTW[index]  = Sail.getLabelWidth(newTitle,"bold 12px verdana");
        this.title[index] = newTitle;
        
        //-------------------------------------------------------------------------------
        //根据索引，修改标题文本显示
        //-------------------------------------------------------------------------------
        var cells = this.div_title_son.el.children[0].rows[0].cells;
        var titleTD = cells[1].children[0].rows[0].cells[5];
        titleTD.innerText = newTitle;

        var TDID = this.div_title.getID()+"-"+index;
        this.setTabClass(TDID,index,(this.activeIndex==index)?true:false);

        //-------------------------------------------------------------------------------
        //判断修改后是否需要 moveBar 如果需要，创建moveBar
        //-------------------------------------------------------------------------------
        //this.resetTabsTitle(index);
        this.reCreateTitleBar();
        //code mark 20090916223400

    },
    
    //===================================================================================
    //方法 ： some func for add or del tab
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    add : function(){
        //debugger;
    },
    
    //===================================================================================
    //方法 ： some func for move button bar 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    needMoveBar       : function(){
        var tw = this.getTabTotalWidth()+20;
        return (tw>(this.width))?true:false;
    },
    
    hideMoveBar       : function(){
        if(this.btMove2Left!=undefined){
            this.btMove2Left.hide();
            this.btMove2Right.hide();
        }
    },
    showMoveBar       : function(){
        if(this.btMove2Left!=undefined){
            this.btMove2Left.show();
            this.btMove2Right.show();
        }
    },
    
    reCreateMoveBar   : function(){
        
        //-------------------------------------------------------------------------------
        if(this.haveMoveBar!==true){    //未创建
            if(this.needMoveBar()){     //需要创建
                this.createMoveBar();   //创建
                return true;
            }
            return false;
        }
        
        //-------------------------------------------------------------------------------
        if(this.needMoveBar()){
            this.showMoveBar();
            var left = this.getMoveButtonLeft();

            this.btMove2Left.setLeft(left);
            this.btMove2Right.setLeft(left+16);
            
            return true;
        }else{
            this.hideMoveBar();
            return false;
        }
    },
    createMoveBar     : function(){
        
        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        var left = this.getMoveButtonLeft();        //获得起始左位置
        this.btMove2Left = new Sail.DIV({           //左移按钮
            left  : left,
            top   : 3,
            width : 15,
            border : "0px #00ff00 solid",
            height: 15,
            parent: this.getOCD(),
            zIndex: 10
        });
        this.btMove2Left.addClass('icon-tabs-m2-left');
        this.btMove2Left.addClass('icon-tabs-m2-left-disabled');
        
        var leftEl = Ext.get(this.btMove2Left.el);
        leftEl.on('mouseover',this.btMove2Left_over,this);
        leftEl.on('mouseout',this.btMove2Left_out,this);
        leftEl.on('click',this.btMove2Left_click,this);

        //-------------------------------------------------------------------------------
        //-------------------------------------------------------------------------------
        this.btMove2Right = new Sail.DIV({          //右移按钮
            left  : left+16,
            top   : 3,
            width : 15,
            border : "0px #00ff00 solid",
            height: 15,
            parent: this.getOCD(),
            zIndex: 10
        });
        this.btMove2Right.addClass('icon-tabs-m2-right');

        var rightEl = Ext.get(this.btMove2Right.el);
        rightEl.on('mouseover',this.btMove2Right_over,this);
        rightEl.on('mouseout',this.btMove2Right_out,this);
        rightEl.on('click',this.btMove2Right_click,this);

        this.haveMoveBar = true;
        
        return this.moveBarWidth;
    },
    
    
    //===================================================================================
    //方法 ： some func for createBody and children 
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    getBodyHeight : function(){
        return this.height-((this.showTitle==true)?26:0)
    },
    
    createBody : function(config){              //创建body
        var bodyHeight = this.getBodyHeight();
        
        var bodyConfig = {
            left  : 0,
            top   : config.top-1||0,
            width : '100%',
            height: bodyHeight+1,
            parent: this.getOCD(),
            zIndex: 11
        };
        
        if(this.border===true){
            bodyConfig.border = '#99BBE8 1px solid';
        }
        if(typeof this.border =='string'){
            bodyConfig.border = this.border;
        }
        bodyConfig.style={};
        bodyConfig.style.overflow='hidden';
        this.body = new Sail.DIV(bodyConfig);
        
        //this.body.el.style.overflow='hidden';
        this.createChildren();
        //debugger;
        return this.body.getEl();
    },

    createChildren : function(){
        
        this.children=[];
        var bodyHeight = this.getBodyHeight();

        for(var i=0;i<this.title.length;i++){
            var childerConfig ={
                left  : 0,
                top   : 0,
                width : '100%',
                height: bodyHeight-1,
                parent: this.body,
                border:'#ff0000 0px solid',
                zIndex: 10
            };
            var td = new Sail.DIV(childerConfig);
            td.el.style.backgroundColor = "#ffffff";
            td.el.style.overflow = 'auto';
            //td.setHTML("-"+(i+1));
            this.children.push(td);
        }
    },
    
    //===================================================================================
    //方法 ：  some func for children layout create
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    afterCreateWidget : function(){
        this.tabLayouts = [];
        
        for(var i=0;i<this.title.length;i++){
            var tabConfiger = this.items[i];
            
            if(tabConfiger==undefined || tabConfiger.items == undefined) {
                this.tabLayouts.push(null);
            }else{
                var layout = new Sail.layoutConstructor({
                    executor     : this.executor,
                    items        : tabConfiger.items,
                    layoutConfig : tabConfiger.layoutConfig,
                    layout       : tabConfiger.layout,
                    parentDiv    : this.children[i],
                    ownerFrame   : this.ownerFrame,
                    ownerGroup   : this.ownerFrame.getChildren(),
                    page         : this.ownerFrame.getBelongedPage(),
                    widgetPrefix : this.ownerFrame.widgetPrefix,
                    height       : this.getBodyHeight(),
                    width        : this.body.getOffset().width,
                    constructTo  : this
                });
                
                this.tabLayouts.push(layout);
            }
            if(i==this.activeIndex){
                this.activedChilder(i,true);
                continue;
            }
            
            if(this.createMode[i]=="when-created"){
                this.doLayoutByIndex(i);
            }
        } 

    },
    
    doLayoutByIndex : function(tabIndex){
        
        if(this.tabLayouts[tabIndex]!=null){


            this.tabLayouts[tabIndex].height = this.getBodyHeight();
            this.tabLayouts[tabIndex].width  = this.body.getOffset().width;

        
            //this.loadMask = new Ext.LoadMask(Ext.get(this.children[tabIndex].el),{msgCls:'x-mask-saveing',msg:"create...."});
            //this.loadMask.show();
            
            this.tabLayouts[tabIndex].doLayout(this.level);
            this.createFlag[tabIndex] = true;
            
            //this.loadMask.hide();
        }
    },
    
    //===================================================================================
    //方法 ：  createWidgetElement
    //参数 ： 
    //返回 :  
    //说明 ： 
    //===================================================================================
    createWidgetElement:function(){
        //debugger;
        var date1 = new Date();

        //-------------------------------------------------------------------------------
        if(this.showTitle===true){
            var h_titleBar = this.createTitleBar();
            var h_splitBar = this.createSplitBar(h_titleBar);     
        }
        
        //-------------------------------------------------------------------------------
        var _top = h_titleBar+h_splitBar;
        this.createBody({top:_top-1});

        var date2 = new Date();

    },
    
    lastFunc : function(){
    }    
});


Sail.widget.ext.tabs = Sail.widget.ext.tabComponent;
